__getattr__
当__getattribute__没有手动定义时,若用户访问了不存在的对象,或者对象的属性不存在时,调用此函数。
__getattribute__
定义此方法后,优先调用。
几个例子:
1. __getattr__
与__getattribute__
的调用顺序
class A:
def __getattr__(self, item):
print(1)
def __getattribute__(self, item):
print(2)
def __setattr__(self, key, value):
print(3)
def __delete__(self, instance):
print(4)
a = A()
a.x
a.x = 10
a.x
print(a.x)
结果
2
3
2
2
None
逐步分析:首先,由于类中没有x,所以当运行a.x
的时候,系统会调用__getattribute__(self, item)
函数,或许会有人疑惑:“哎?为什么x这个属性明明没有设定,但却调用了__getattribute__(self, item)
?为什么没有调用<