'Can't set attribute' with new-style properties in Python

I'm trying to use new-style properties declaration:

class C(object):
    def __init__(self):
        self._x = 0

    @property
    def x(self):
        print 'getting'
        return self._x

    @x.setter
    def set_x(self, value):
        print 'setting'
        self._x = value

if __name__ == '__main__':
    c = C()
    print c.x
    c.x = 10
    print c.x

and see the following in console:

pydev debugger: starting
getting
0
File "\test.py", line 55, in <module>
c.x = 10
AttributeError: can't set attribute

what am I doing wrong? P.S.: Old-style declaration works fine.


The documentation says the following about using decorator form of property:

Be sure to give the additional functions the same name as the original property (x in this case.)

I have no idea why this is since if you use property as function to return an attribute the methods can be called whatever you like.

So you need to change your code to the following:

@x.setter
def x(self, value):
    'setting'
    self._x = value

The setter method has to have the same name as the getter. Don't worry, the decorator knows how to tell them apart.

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