Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 270
Maxim Popravko Avatar asked Nov 15 '10 10:11

Maxim Popravko


People also ask

Can not set attribute Python?

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.

How do I fix attribute error in Python?

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.

What is __ Getattr __?

__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.


1 Answers

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 
like image 198
Dave Webb Avatar answered Sep 26 '22 06:09

Dave Webb