例如,我使用以下代码:
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()
当运行时出现“最大递归深度超过”错误。请问我在这里做错了什么?
__init__
方法中构建self.dict1
时,您试图访问self.A
。这会触发对__getattr__
的调用,它假定存在self.dict1
。 - holdenwebself.dict1['B'] = self.A
。 - M1k3__setattr__
方法,那么__init__
方法应该使用self.__dict__['dict1'] = {}
。 - holdenweb