Unable to set attribute with new style properties in Python

I am trying to use new style property 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 cx cx = 10 print cx 

and see the following in the console:

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

what am I doing wrong? PS: The old style declaration works great.

+52
python
Nov 15 '10 at 10:27
source share
3 answers

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

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

I have no idea why this happens, if you use property as a function to return an attribute, methods can be called as you like.

So, you need to change your code to the following:

 @x.setter def x(self, value): 'setting' self._x = value 
+75
Nov 15 '10 at 10:38
source share

The installation method must have the same name as the recipient. Don't worry, the decorator knows how to tell them apart.

 @x.setter def x(self, value): ... 
+13
Nov 15 '10 at
source share

When you call @ x.setter, @ x.getter or @ x.deleter, you create a new property object and give it the name of the function you are decorating. So it’s really important that the last time you use the @x decorator. * Er in the class definition, it has a name that you really want to use. But since this will leave your class namespace contaminated with incomplete versions of the property you want to use, it is best to use the same name to clean them.

+5
Nov 01 2018-11-11T00:
source share



All Articles