Overriding properties
Leif K-Brooks
eurleif at ecritters.biz
Sat Dec 11 20:43:44 EST 2004
Nick Patavalis wrote:
> Why does the following print "0 0" instead of "0 1"? What is the
> canonical way to rewrite it in order to get what I obviously expect?
>
> class C(object):
<snip>
> value = property(get_value, set_value)
>
> class CC(C):
> def set_value(self, val):
<snip>
> c.value = -1
> cc.value = -1
> print c.value, cc.value
The problem is that the names get_value and set_value are evaluated only
once: when class C is first defined. The property has no knowledge of
(or interest in) the fact that a different function named set_value has
been defined.
There are several ways to fix it. The simplest would be to create a new
property object in CC's definition:
class CC(C):
def set_value(self, val):
if val < 0:
self.__val = 1
else:
self.__val = val
value = property(C.get_value, set_value)
But an easier, more flexible method would be to use a metaclass which
automatically adds properties for specially-named methods. One example
of such a metaclass is autoprop from Guido van Rossum's descrintro
essay; see <URL:http://www.python.org/2.2.3/descrintro.html>.
More information about the Python-list
mailing list