• Python之__getattr__和__getattribute__介绍


    __getattr__和__getattribute__方法介绍

    __getattr__方法

        重载__getattr__方法对类及其实例未定义的属性有效。也就属性是说,如果访问的属性存在,就不会调用__getattr__方法。这个属性的存在,包括类属性和实例属性。当访问的属性不存在的时候,就会调用该方法

     1 class Person:
     2     def __init__(self, name, age):
     3         self.name = name
     4         self.age = age
     5         
     6     def __getattr__(self, item):
     7         return "hello world"
     8         
     9 
    10 p = Person("xiexie", 21)
    11 print(p.sex)
    12     
    hello world
    
    
    ------------------
    (program exited with code: 0)
    
    请按任意键继续. . .

    可以看到上面代码中访问不存在的属性时,会执行__getattr__方法

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
        """
        def __getattr__(self, item):
            return "hello world"
        """
            
    
    p = Person("xiexie", 21)
    print(p.sex)
        
    Traceback (most recent call last):
      File "proxy.py", line 12, in <module>
        print(p.sex)
    AttributeError: 'Person' object has no attribute 'sex'
    
    
    ------------------
    (program exited with code: 1)
    
    请按任意键继续. . .

    当注释掉该方法后,发现会报错,提示对象没有该属性

    __getattribute__方法

     1 class Person:
     2     def __init__(self, name, age):
     3         self.name = name
     4         self.age = age
     5 
     6     def __getattribute__(self, item):
     7         return "hello world"
     8         
     9 
    10 p = Person("xiexie", 21)
    11 print(p.sex)
    12 print(p.name)
    13     
    hello world
    hello world
    
    
    ------------------
    (program exited with code: 0)
    
    请按任意键继续. . .

    可以看到,当有方法__getattribute__后,不论对象的属性是否存在,都会进入__getattribute__执行操作。

    当同时定义__getattribute__和__getattr__时,__getattr__方法不会再被调用,除非显示调用__getattr__方法或引发AttributeError异常。

    当父类有__getattribute__方法,子类没有时,当子类用.形式查找属性时也会调用父类的该方法

     1 class Person:
     2     def __init__(self, name, age):
     3         self.name = name
     4         self.age = age
     5 
     6     def __getattribute__(self, item):
     7         return "hello world"
     8         
     9 
    10 class Me(Person):
    11     def __init__(self, name, age):
    12         self.name = name
    13         self.age = age
    14         
    15 
    16 p = Me("xiexie", 21)
    17 print(p.sex)
    18 print(p.name)
    19     
    hello world
    hello world
    
    
    ------------------
    (program exited with code: 0)
    
    请按任意键继续. . .

    更详细的介绍可以参考下面的链接

    https://www.cnblogs.com/blackmatrix/p/5681480.html

  • 相关阅读:
    无法启动调试--未安装 Silverlight Developer 运行时。请安装一个匹配版本。
    jQuery导航菜单防刷新
    IE6下Png透明最佳解决方案(推荐) Unit PNG Fix
    每周进步要点(第50周12.4-12.11)
    学习笔记:重塑你的自我驱动力
    学习笔记之是什么决定我们的命运
    读书《万万没想到 3》
    人与人之间的鄙视链是如何形成的?
    第7本《万万没想到-用理工科思维理解世界2》
    中明写公众号的时候他在想什么
  • 原文地址:https://www.cnblogs.com/xiebinbbb/p/13722552.html
Copyright © 2020-2023  润新知