Issue with assigning (or overloading) an assignment operator in Python

I'm having trouble assigning an assignment operator.

I successfully reloaded __setattr__. But after initializing the object, I want it to __setattr__do something else, so I'm trying to assign it to another function __setattr2__.

the 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
+5
source share
2 answers

From the docs :

Special Method Finder for New 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()
+8

, , __init__ ?

class C(object):
    def __init__(self):
        # Use the superclass __setattr__ because we've overridden our own.
        super(C, self).__setattr__('initialising', True)
        self.x = 0
        # the very last thing we do in __init__ is indicate that it finished
        super(C, self).__setattr__('initialising', False)

    def __setattr__(self, name, value):
        if self.initialising:
            print "during __init__, setting", name
            # I happen to like super() rather than explicitly naming the superclass
            super(C, self).__setattr__(name, value)
        else:
            print "after __init__, setting", name
            super(C, self).__setattr__(name, value)
+3

All Articles