Python 2 __getattr__最大递归深度

问题描述:

例如,我使用以下代码:

for example i use this code:

class A(object):
    def __init__(self):
        self.dict1 = {
            'A': 3,
            'B': self.A}
    def __getattr__(self, key):
        if key in self.dict1:
            return self.dict1[key]
a = A()

,运行时会抛出超过最大递归深度的信息. 有人可以告诉我我在做什么错

and when it's runned it throws maximum recursion depth exceeded. Can someone please tell me what am i doing wrong here

__getattr__方法中对self.dict1的引用会导致再次调用__getattr__,依此类推,从而实现了无限递归.在__getattr__中访问self属性的唯一安全方法是使用对self.__dict__的引用.试试

The reference to self.dict1 inside your __getattr__ method causes __getattr__ to be called again, and so on, hence the infinite recursion. The only safe way to access attributes of self inside __getattr__ is by using references to self.__dict__. Try

def __getattr__(self, key):
    if key in self.__dict__['dict1']:
        return self.__dict__['dict1'][key]

还请注意,缺少else子句将意味着未定义的属性似乎具有值None.

Note also that the absence of an else clause will mean undefined attributes appear to have the value None.