[英]Python 2 __getattr__ max recursion depth
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 有人可以告诉我我在做什么错
The reference to self.dict1
inside your __getattr__
method causes __getattr__
to be called again, and so on, hence the infinite recursion. __getattr__
方法中对self.dict1
的引用导致__getattr__
被再次调用,依此类推,因此无限递归。 The only safe way to access attributes of self
inside __getattr__
is by using references to self.__dict__
. 在__getattr__
内部访问self
属性的唯一安全方法是使用对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
. 还请注意,缺少else
子句将意味着未定义的属性似乎具有值None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.