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'}
呵呵,谢谢
VaTG790i.最好的<a href=http://www.kyfei.com>网站推广软件</a>,
非常好
....................
;ui;普i;uighur;ui;ui;个
在unix网络编程中看到了关于TCP/IP的一些内容,我感觉还是写的不够。正在下载中,一定
下载地址呢