Adding modified methods from another class without subclassing
John O'Hagan
research at johnohagan.com
Mon Aug 22 09:08:50 EDT 2011
On Mon, 22 Aug 2011 15:27:36 +1000
Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> 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
Thanks, this looks promising. I didn't know about __getattr__ or delegation. This example doesn't seem to work as is for special methods beginning with "__" (e.g.: "TypeError: object of type 'MyList' has no len()"). It seems that __getattr__ is not called for special methods. Also, it doesn't immediately suggest to me a way of modifying method calls (maybe __setattr__?). But it's certainly a neater way to get methods to operate on the attribute. I'm looking into it, and delegation generally.
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)?
Thanks and regards,
John
More information about the Python-list
mailing list