Trouble with assigning (or re-overloading) the assignment operator in Python

python

Solution

From the docs:

Special method lookup for new-style classes

For new-style classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary. That behaviour is the reason why the following code raises an exception (unlike the equivalent example with old-style classes):

>>> class C(object):
...     pass
...
>>> c = C()
>>> c.__len__ = lambda: 5
>>> len(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'C' has no len()

Problem

I'm having trouble assigning the assignment operator. I have successfully overloaded `__setattr__`. But after the object is initialized, I want `__setattr__` to do something else, so I try assigning it to be another function, `__setattr2__`. Code: ``` class C(object): def __init__(self): self.x = 0 self.__setattr__ = self.__setattr2__ def __setattr__(self, name, value): print "first, setting", name object.__setattr__(self, name, value) def __setattr2__(self, name, value): print "second, setting", name object.__setattr__(self, name, value) c = C() c.x = 1 ``` What I get: ``` first, setting x first, setting __setattr__ first, setting x ``` What I want/expect: ``` first, setting x first, setting __setattr__ second, setting x ```

Original source