I know that you can’t call object.__setattr__ on objects not inherited from object, but is there anything else that is different between the two? I’m working in Python 2.6, if this matters.
I know that you can’t call object.__setattr__ on objects not inherited from object ,
Share
Reading this question again I misunderstood what @paper.cut was asking about: the difference between classic classes and new-style classes (not an issue in Python 3+). I do not know the answer to that.
Original Answer*
setattr(instance, name, value)is syntactic sugar forinstance.__setattr__(name, value)**.You would only need to call
object.__setattr__(...)inside a class definition, and then only if directly subclassingobject— if you were subclassing something else,Spamfor example, then you should either usesuper()to get the next item in the heirarchy, or callSpam.__setattr__(...)— this way you don’t risk missing behavior that super-classes have defined by skipping over them directly toobject.* applies to Python 3.0+ classes and 2.x new-style classes
**There are two instances where
setattr(x, ...)andx.__setattr__(...)are not the same:xitself has a__setattr__in it’s private dictionary (sox.__dict__[__setattr__] = ...(this is almost certainly an error)x.__class__has a__getattribute__method — because__getattribute__intercepts every lookup, even when the method/attribute existsNB
These two caveats apply to every syntactic sugar shortcut:
setattrgetattrlenboolhash