built-in 'property'

Steven Bethard steven.bethard at gmail.com
Tue Dec 28 13:06:56 EST 2004


Stian Søiland wrote:
> On 2004-12-28 12:05:20, Bob.Cowdery at CGI-Europe.com wrote:
> 
> 
>>class NOTOK(object):
>>    
>>    def __init__(self):
>>        self.__x = 0
>>        self.x = property(self.getx, self.setx, self.delx, "I'm the 'x'
>>property.")
>>        
>>    def getx(self): return self.__x - 5
>>    def setx(self, value): self.__x = value + 10
>>    def delx(self): del self.__x

I seem to be missing some of the messages on this thread, but while 
we're talking about properties, it's probably instructive to remind 
people that the functions passed to the property function are not 
redefinable in subclasses:

py> class D(C):
...     def getx(self):
...         return 42
...
py> D(5).x
5
py> class C(object):
...     def getx(self):
...         return 1
...     x = property(getx)
...
py> class D(C):
...     def getx(self):
...         return 42
...
py> C().x
1
py> D().x
1

Note that even though I redefined getx in class D, the 'x' property is 
still using the function C.getx that was passed into it.

For this reason, I usually suggest declaring properties like[1]:

py> class E(object):
...     def x():
...         def get(self):
...             return float(self._x)
...         def set(self, x):
...             self._x = x**2
...         return dict(fget=get, fset=set)
...     x = property(**x())
...     def __init__(self, x):
...         self._x = x
...
py> e = E(42)
py> e.x
42.0
py> e.x = 3
py> e.x
9.0

Note that by using the x = property(**x()) idiom, I don't pollute my 
class namespace with get/set/del methods that aren't really useful to 
instances of the class.  It also makes it clear to subclasses that if 
they want different behavior from the x property that they'll need to 
redefine the entire property, not just a get/set/del method.

Steve

[1] Thanks to whoever originally suggested this! Sorry, I've forgotten 
who...



More information about the Python-list mailing list