Object-based inheritance in Python

Tobias Windeln Tobias.Windeln at gmx.de
Fri Jan 9 12:39:48 CET 2004


I'm looking for suggestions on object-based inheritance
in Python. Automatic forwarding (often called delegation)
in Python is easy:

def __getattr__(self, attr):
     return getattr(self.delegatee, attr)
def __setattr__(self, attr, value):
     return setattr(self.delegatee, attr, value)

Maybe there is a way to hand over self to the delegatee object.
So the next call on self in the delegatee object is send to the child 

A small example:

class Child:
     def __init__(self, delegatee):
         self.__dict__['delegatee'] = delegatee

# TODO ... delegation/overriding mechanism ....

     def m(self):
     def m3(self):

class Delegatee:
     def m2(self):
     def m3(self):


 >>> c = Child(Delegatee())
 >>> c.m()

The call to m2() is forwarded to the Delegatee.
The call to m3() in m2() is redirected to Child and
the m3() Method in Child is called:
	child   -------------------->   delegatee

This functionality would be helpfull in Patterns (Decorator, Strategy, etc.)

Do you have any suggestions on how to hand over self to the delegatee?
Since the first argument of every method in Python is self, the rest of 
the object-based inheritance works automatically!

I usually work with Java, where I implemented this functionality with 
enormous effort. When I saw Pythons reflective capabilities (__getattr__ 
etc.) I wondered if this is possible in an generic/easy way.

Thanks in advance

More information about the Python-list mailing list