Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top