decorator - Why does @foo.setter in Python not work for me? -
so, i'm playing decorators in python 2.6, , i'm having trouble getting them work. here class file:
class testdec: @property def x(self): print 'called getter' return self._x @x.setter def x(self, value): print 'called setter' self._x = value
what thought meant treat x
property, call these functions on , set. so, fired idle , checked it:
>>> testdec import testdec testdec import testdec >>> t = testdec() t = testdec() >>> t.x t.x called getter traceback (most recent call last): file "<stdin>", line 1, in <module> file "testdec.py", line 18, in x return self._x attributeerror: testdec instance has no attribute '_x' >>> t.x = 5 t.x = 5 >>> t.x t.x 5
clearly first call works expected, since call getter, , there no default value, , fails. ok, good, understand. however, call assign t.x = 5
seems create new property x
, , getter doesn't work!
what missing?
you seem using classic old-style classes. in order properties work correctly need use new-style classes instead (inherit object
). declare class myclass(object)
:
class testdec(object): @property def x(self): print 'called getter' return self._x @x.setter def x(self, value): print 'called setter' self._x = value
it works:
>>> k = testdec() >>> k.x called getter traceback (most recent call last): file "<stdin>", line 1, in <module> file "/devel/class_test.py", line 6, in x return self._x attributeerror: 'testdec' object has no attribute '_x' >>> k.x = 5 called setter >>> k.x called getter 5 >>>
Comments
Post a Comment