Property in derived class

Ian Kelly ian.g.kelly at gmail.com
Fri May 9 18:58:08 EDT 2008


On Fri, May 9, 2008 at 3:20 PM, Joseph Turian <turian at gmail.com> wrote:
> Could someone demonstrate how to implement the proposed solutions that
> allow the property to be declared in the abstract base class, and
> refer to a get function which is only implemented in derived classes?

One way is to have the property refer to a proxy that performs the
late binding, which might look something like this:

    def _bar(self):
        return self.bar()

    prop = property(fget=_bar)

Another way is to declare properties using something like the
following indirectproperty class.  I haven't thoroughly tested this,
so I don't know whether it works exactly right.

class indirectproperty(object):

    def __init__(self, sget=None, sset=None, sdel=None):
        self.sget = sget
        self.sset = sset
        self.sdel = sdel

    def __get__(self, instance, owner):
        if instance is not None:
            fget = getattr(instance, self.sget)
        else:
            fget = getattr(owner, self.sget)
        return fget()

    def __set__(self, instance, value):
        fset = getattr(instance, self.sset)
        fset(value)

    def __delete__(self, instance):
        fdel = getattr(instance, self.sdel)
        fdel()


class Foo(object):
    def func(self): return "foo"
    callfunc = indirectproperty(sget="func")

class Bar(Foo):
    def func(self): return "bar"



More information about the Python-list mailing list