在官方文档中,当 __getattribute__ 引发 AttributeError 时,将调用 __getattr__。 但是代码并没有进入死循环,为什么?
class A:
def __getattr__(self, item):
return self.__getattribute__(item)
a = A()
print(a.d)
就是抛出一个AttributeError,怎么解释呢?
请您参考如下方法:
此调试print 将帮助您了解正在发生的事情:
class A:
def __getattr__(self, item):
print('__getattr__ called for item {}'.format(item))
return self.__getattribute__(item)
def __getattribute__(self, item):
print('__getattribute__ called for item {}'.format(item))
return object.__getattribute__(self, item)
a = A()
print(a.d)
输出:
__getattribute__ called for item d
__getattr__ called for item d
__getattribute__ called for item __getattribute__
__getattribute__ called for item d
AttributeError: 'A' object has no attribute 'd'
__getattribute__首先被调用。__getattribute__查找算法失败后调用__getattr__。- 在
self.__getattribute__中,还为项目__getattribute__调用了__getattribute__。 - 现在为item d调用了
__getattribute__,但是因为是直接调用的,所以不在查找算法的流程中,所以不会调用__getattr__。 object.__getattribute__(self, item)找不到d因此引发错误。
