[Python-Dev] Definining properties - a use case for class decorators?
Guido van Rossum
guido at python.org
Tue Oct 18 04:24:36 CEST 2005
[Guido]
> > Let's change the property built-in so that its arguments can be either
> > functions or strings (or None). If they are functions or None, it
> > behaves exactly like it always has.
> >
> > If an argument is a string, it should be a method name, and the method
> > is looked up by that name each time the property is used. Because this
> > is late binding, it can be put before the method definitions, and a
> > subclass can override the methods. Example:
> >
> > class C:
> >
> > foo = property('getFoo', 'setFoo', None, 'the foo property')
> >
> > def getFoo(self):
> > return self._foo
> >
> > def setFoo(self, foo):
> > self._foo = foo
> >
> > What do you think?
[Barry]
> Ick, for all the reasons that strings are less appealing than names.
I usually wholeheartedly agree with that argument, but here I don't
see an alternative.
> IMO, there's not enough advantage in having the property() call before
> the functions than after.
Maybe you didn't see the use case that Greg had in mind? He wants to
be able to override the getter and/or setter in a subclass, without
changing the docstring or having to repeat the property() call. That
requires us to do a late binding lookup based on a string.
Tim Delaney had a different solution where you would pass in the
functions but all it did was use their __name__ attribute to look up
the real function at runtime. The problem with that is that the
__name__ attribute may not be what you expect, as it may not
correspond to the name of the object passed in. Example:
class C:
def getx(self): ...something...
gety = getx
y = property(gety)
class D(C):
def gety(self): ...something else...
Here, the intention is clearly to override the way the property's
value is computed, but it doesn't work right -- gety.__name__ is
'getx', and D doesn't override getx, so D().y calls C.getx() instead
of D.gety().
If you can think of a solution that looks better than mine, you're a genius.
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev
mailing list