Python error saying "AttributeError: can't set attribute"
I'm trying to execute the following python code:
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
But I get the following attributeerror: can't set attribute:
pydev debugger: starting
getting
0
File "test.py", line 55, in
c.x = 10
AttributeError: can't set attribute
The reason you are getting this error “attributeerror: can't set attribute” is that you are naming the setter method incorrectly. You have named the setter method as set_x which is incorrect, that’s why you are getting the Attribute Error.
To fix this error, instead of naming it as set_x you need to give it the same name as the property you creating a setter for, in your case, you can do it like this:
@x.setter
def x(self, value):
'setting'
self._x = value