__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