Python 2 __getattr__ max recursion depth

后端 未结 1 1648
滥情空心
滥情空心 2021-01-05 17:55

for example i use this code:

class A(object):
    def __init__(self):
        self.dict1 = {
            \'A\': 3,
            \'B\': self.A}
    def __getat         


        
相关标签:
1条回答
  • 2021-01-05 18:36

    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]
    

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

    0 讨论(0)
提交回复
热议问题