Adding modified methods from another class without subclassing

John O'Hagan research at johnohagan.com
Mon Aug 22 20:55:26 EDT 2011


On Mon, 22 Aug 2011 23:08:50 +1000
John O'Hagan <research at johnohagan.com> wrote:

> On Mon, 22 Aug 2011 15:27:36 +1000
> Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
[..]
> > 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
> 
[..]
> 
> However, I don't understand what the super call is doing. If the method isn't delegated, shouldn't it just fall back to getattr(self, name)?

On reading the __getattr__ docs properly, I see that AttributeError is what should generally happen.
 
> Thanks and regards,
> 
> John
> 




More information about the Python-list mailing list