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?

mgilson
  • 300,191
  • 65
  • 633
  • 696
Mattia
  • 47
  • 1
  • 9
  • `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. –  May 30 '13 at 16:01

1 Answers1

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696