getattr - Python 2 __getattr__ max recursion depth -
for example use 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()
and when it's runned throws maximum recursion depth exceeded. can please tell me doing wrong here
the reference self.dict1
inside __getattr__
method causes __getattr__
called again, , on, hence infinite recursion. safe way access attributes of self
inside __getattr__
using references self.__dict__
. try
def __getattr__(self, key): if key in self.__dict__['dict1']: return self.__dict__['dict1'][key]
note absence of else
clause mean undefined attributes appear have value none
.
Comments
Post a Comment