0

I know that you should be aware while redefine setattr method that you could end in a loop.

I know there's two solution to avoid loops:

1) using object superclass, calling :

object.__setattr__(instance,attr,value)

2) using the class dict:

self.__dict__[attr] = value

My question is, shouldn't the __dict__ solution end up in a loop too? and why it isn't?

Is because that way we're calling the __setattr__ of the __dict__ object (everything is an object) or what?

And if so, shouldn't it work the same for everything?

1
  • a[b] = c doesn't set an attribute. It sets an item. It's a different thing both conceptually and w.r.t. dunder methods involved. Commented May 30, 2013 at 16:01

1 Answer 1

5

Why would you expect it to end up in a loop?

instance.__dict__[attr] = value is basically what object.__setattr__(instance,attr,value) does (for normal attributes). Note that __dict__[attr] = whatever does not call __setattr__ at all. It calls __setitem__ which is a different method entirely.

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

3 Comments

It also calls it on an entirely different object.
@delnan -- True. Of course, using __getattribute__ you can get into the infinite loop using self.__dict__, but ...
So it is because is calling setitem or because is a different object? thanks guys

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.