当前位置: 主页 > 日志 > Python >

why __getattr__ raise RuntimeError: maximum recursion depth exceeded ?

i want to create a dictionary which support attribute. so i do the following test.

# by redice 2011.03.05
class myDic:
    def __init__(self):
        self.d = dict()
        
    def __getattr__(self, name):
        return self.d.get(name)

    def __setattr__(self, name, value):
        self.d[name] = value


if __name__ == '__main__':
    m = myDic()
    m.name = 'redice'
    print m.name

the program appears a exception:

RuntimeError: maximum recursion depth exceeded

 

the debugger tell me this exception raise in __getattr__, why?

 

when we use m.name,  the class will firstly find name in __dict__ (myDic.__dict__ then self.__dict__),  if not found , __getattr__ will be called.

so when myDic initialized,  __init__ is called,  when run to self.d, the class will find d in __dict__ first, but faild, so __getattr__ be called. but  unfortunately,  self.d appear again in the __getattr__. so a endless loop  comes into being.

 

since we know the reason, we can modify the code  as following.

 

 

class myDic:
    d = dict()

    def __getattr__(self, name):
        return self.d.get(name)

    def __setattr__(self, name, value):
        self.d[name] = value


if __name__ == '__main__':
    m = myDic()
    m.name = 'redice'
    m.sex = 'male'
    print m.name
    print m.d

 

the output:

 

 

redice

{'name': 'redice', 'sex': 'male'}

 

[日志信息]

该日志于 2011-03-05 17:16 由 redice 发表在 redice's Blog ,你除了可以发表评论外,还可以转载 “why __getattr__ raise RuntimeError: maximum recursion depth exceeded ?” 日志到你的网站或博客,但是请保留源地址及作者信息,谢谢!!    (尊重他人劳动,你我共同努力)
   
验证(必填):   点击我更换验证码

redice's Blog  is powered by DedeCms |  Theme by Monkeii.Lee |  网站地图 |  本服务器由西安鲲之鹏网络信息技术有限公司友情提供

返回顶部