decorator – Why does @foo.setter in Python not work for me?

decorator – Why does @foo.setter in Python not work for me?

You seem to be using classic old-style classes in python 2. In order for properties to work correctly you need to use new-style classes instead (in python 2 you must inherit from object). Just declare your class as MyClass(object):

class testDec(object):

    @property
    def x(self): 
        print called getter
        return self._x

    @x.setter
    def x(self, value): 
        print called setter
        self._x = value

It works:

>>> k = testDec()
>>> k.x
called getter
Traceback (most recent call last):
  File <stdin>, line 1, in <module>
  File /devel/class_test.py, line 6, in x
    return self._x
AttributeError: testDec object has no attribute _x
>>> k.x = 5
called setter
>>> k.x
called getter
5
>>> 

Another detail that might cause problems is that both methods need the same name for the property to work. If you define the setter with a different name like this it wont work:

@x.setter
def x_setter(self, value):
    ...

And one more thing that is not completely easy to spot at first, is the order: The getter must be defined first. If you define the setter first, you get name x is not defined error.

Just a note for other people who stumble here looking for this exception: both functions need to have the same name. Naming the methods as follows will result in an exception:

@property
def x(self): pass

@x.setter
def x_setter(self, value): pass

Instead give both methods the same name

@property
def x(self): pass

@x.setter
def x(self, value): pass

It is also important to note that the order of the declaration matters. The getter must be defined before the setter in the file or else you will get a NameError: name x is not defined

decorator – Why does @foo.setter in Python not work for me?

You need to use new-style classes which you do by deriving your class from object:

class testDec(object):
   ....

Then it should work.

Leave a Reply

Your email address will not be published. Required fields are marked *