8

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

2
  • 4
    You mention __setattr__ but it is not in your code. Please explain how you are using __setattr__, if you are. Commented Jun 21, 2012 at 19:38
  • 1
    Try adding something like: if item in ["list1","list2"]: return self.__dict__[item] at the start of __getattr__(). Commented Jun 21, 2012 at 19:43

1 Answer 1

13

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.