Skip to main content
 首页 » 编程设计

python之__getattr__中调用__getattribute__会无限大吗

2024年11月24日8rubylouvre

在官方文档中,当 __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 因此引发错误。