Really virtual properties

Bengt Richter bokr at oz.net
Thu Aug 18 21:21:59 EDT 2005


On Thu, 18 Aug 2005 23:36:58 +0200, Torsten Bronger <bronger at physik.rwth-aachen.de> wrote:

>Hallöchen!
>
>When I use properties in new style classes, I usually pass get/set
>methods to property(), like this:
>
>    x = property(get_x)
>
>If I overwrite get_x in a derived class, any access to x still calls
>the base get_x() method.  Is there a way to get the child's get_x()
>method called instead?
>
>(I found the possibility of using an intermediate method _get_x
>which calls get_x but that's ugly.)
>
I think this idea of overriding a property access function is ugly in any case,
but you could do something like this custom descriptor (not tested beyond
what you see here):

 >>> class RVP(object):
 ...     def __init__(self, gettername):
 ...         self.gettername = gettername
 ...     def __get__(self, inst, cls=None):
 ...         if inst is None: return self
 ...         return getattr(inst, self.gettername)()
 ...
 >>> class Base(object):
 ...     def get_x(self): return 'Base get_x'
 ...     x = RVP('get_x')
 ...
 >>> class Derv(Base):
 ...     def get_x(self): return 'Derv get_x'
 ...
 >>> b = Base()
 >>> d = Derv()
 >>> b.x
 'Base get_x'
 >>> d.x
 'Derv get_x'

But why not override the property x in the derived subclass instead,
with another property x instead of the above very questionable trick? I.e.,

 >>> class Base(object):
 ...     x = property(lambda self: 'Base get_x')
 ...
 >>> class Derv(Base):
 ...     x = property(lambda self: 'Derv get_x')
 ...
 >>> b = Base()
 >>> d = Derv()
 >>> b.x
 'Base get_x'
 >>> d.x
 'Derv get_x'

Regards,
Bengt Richter



More information about the Python-list mailing list