Generic optional delegation: is it possible?

Jeff Epler jepler at unpythonic.net
Thu Mar 13 12:49:08 EST 2003


You can do this by subclassing object and using the new __getattribute__


class Delegate:
  def m(self):
    print "Delegate"

class SuperClass(object):
  def m(self):
    print "SuperClass"

class Delegating(SuperClass):
    def __init__(self, delegate=None):
        self.__delegate = delegate

    def __getattribute__(self, attr):
        if attr.endswith("__delegate"):
            return object.__getattribute__(self, attr)
        d = self.__delegate
        if d is not None and hasattr(d, attr):
            return getattr(d, attr)
        return object.__getattribute__(self, attr)

d = Delegate()
o1 = Delegating(d)
o2 = Delegating()
o1.m()
o2.m()





More information about the Python-list mailing list