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.
How is it possible? The explanation you are getting this error is that you are naming the setter method mistakenly. You have named the setter method as set_x which is off base, this is the reason you are getting the Attribute Error.
To avoid the AttributeError in Python code, a check should be performed before referencing an attribute on an object to ensure that it exists. The Python help() function can be used to find out all attributes and methods related to the object.
__getattr__(self, name) Is an object method that is called if the object's properties are not found. This method should return the property value or throw AttributeError . Note that if the object property can be found through the normal mechanism, it will not be called.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With