I have some questions regarding the following code:
1 class Test(object):
2 def __init__(self):
3 print "Object instance created."
4 self._x = raw_input("Initial value of x = ")
5 print "Initial value of x set."
6
7 def Property(func):
8 return property(**func())
9
10 @Property
11 def x():
12 def fget(self):
13 print 'Getting x'
14 return self._x
15 def fset(self, val):
16 print 'Setting x'
17 self._x = val
18 def fdel(self):
19 print 'Deleting x'
20 del self._x
21 doc = "A test case"
22 return locals()
- Why is the
Property()function necessary? - Why can’t I just
return locals()and then use@propertyas a decorator directly?
When I do that I get an error saying x takes no arguments, one given (presumably ‘self’). I know python has the @x.setter option, however I’m forced to use 2.4 regularly, so it’s not an option for me. Even then, @x.setter still seems less elegant than defining it all in one block.
Is there a way to define it all in one block using @property?
You can’t use
propertyas a decorator directly for the code you have posted because it was not designed to be used that way, and it won’t work.If used as a decorator,
propertyconverts the function into the getter; if used as a function, you can pass in the getter, setter, deleter, and a doc.locals()returns all the locals, so you would have a dictionary withfget,fset,fdel,doc,Property, and__init__— causingpropertyto blow up because it was passed too many arguments.Personally, I like the
@x.setterand@x.deleterstyle, as I don’t end up with unnecessary function names in the class name space.If you have to use 2.4 regularly, just roll your own (or steal the latest from 2.6 like I did ;):