I have the declared a class in following way
class A:
def __init__(self, list_1, list_2):
self.list1 = list_1
self.list2 = list_2
def __getattr__(self, item):
if item in self.list1: return "It is in list 1"
elif item in self.list2: return "It is in list 2"
else: return "It is in neither list 1 nor list 2"
Here when I am adding __setattr__ self.list1 goes recursive, since __getattr__ get called after every self.list1 and this recursion is unstoppable. Can you please help me out with it. I need to implement like this.
Thanks
First of all, this is a totally bizarre usage of
__getattr__, but I’ll assume that you know that.Basically, the problem is that
__setattr__is always called every time you do something likeself.foo = bar, so if you use that within__setattr__you’ll end up with the recursion that you got. What you need to do is insert the value that you’re trying to set directly into__dict__self.__dict__['foo'] = bar.If you’re using new style classes (i.e.
Ais a descendant ofobject), then you could also dosuper(A, self).__setattr__(item, value)or even justobject.__setattr__(self, item, value)