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.list
1 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 like self.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. A
is a descendant of object
), then you could also do super(A, self).__setattr__(item, value)
or even just object.__setattr__(self, item, value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With