So, I"m playing with decorators in Python 2.6, and I"m having some trouble getting them to work. Here is my 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 I thought this meant is to treat
x like a property, but call these functions on get and set. So, I fired up IDLE and checked it:
>>> from testDec import testDec from 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 the first call works as expected, since I call the getter, and there is no default value, and it fails. OK, good, I understand. However, the call to assign
t.x = 5 seems to create a new property
x, and now the getter doesn"t work!
What am I missing?
You seem to be using classic old-style classes in python 2. In order for properties to work correctly you need to use new-style classes instead (in python 2 you must inherit from
object). Just declare your class as
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
>>> 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 >>>
Another detail that might cause problems is that both methods need the same name for the property to work. If you define the setter with a different name like this it won"t work:
@x.setter def x_setter(self, value): ...
And one more thing that is not completely easy to spot at first, is the order: The getter must be defined first. If you define the setter first, you get
name "x" is not defined error.
Python Data Science Handbook: Essential Tools for Working with Data - PDF, 1st Edition For many researchers, Python is a first-class tool, primarily because of its libraries for storing, manipulati...
Python Crash Course is the world's best-selling guide to the Python programming language. This quick and in-depth introduction to Python programming will get you started writing programs, solving prob...
This book project was first presented to me during my first week in my current role of managing the data mining development at SAS. Writ- ing a book has always been a bucket‐list item, and I was ver...
This encyclopedia will be an indispensable resource for our time as it reflects the fact that we are currently living in an expanding data-driven world. ...