Adding modified methods from another class without subclassing

Steven D'Aprano steve+comp.lang.python at
Mon Aug 22 01:27:36 EDT 2011

On Mon, 22 Aug 2011 03:04 pm John O'Hagan wrote:

> The "pitches" attribute represents the instances and as such I found
> myself adding a lot of methods like:
> def __getitem__(self, index):
>     return self.pitches[index]
> def __len__(self):
>     return len(self.pitches)

Looks like a call for (semi-)automatic delegation!

Try something like this:

# Untested
class MySeq(object):
    methods_to_delegate = ('__getitem__', '__len__', ...)
    pitches = ...  # make sure pitches is defined
    def __getattr__(self, name):
        if name in self.__class__.methods_to_delegate:
            return getattr(self.pitches, name)
        return super(MySeq, object).__getattr__(self, name)
        # will likely raise AttributeError

> But the fact that I haven't seen this approach before increases the
> likelihood it may not be a good idea. I can almost hear the screams of
> "No, don't do that!" 

The general technique is called delegation and is perfectly legitimate.


More information about the Python-list mailing list