Python 2 __getattr__ max recursion depth

寵の児 提交于 2019-11-30 18:06:42

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/34828857/python-2-getattr-max-recursion-depth

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!