Adding modified methods from another class without subclassing

John O'Hagan research at johnohagan.com
Wed Aug 24 07:09:28 EDT 2011


On Tue, 23 Aug 2011 17:25:22 +1000
Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:

> On Mon, 22 Aug 2011 11:08 pm John O'Hagan wrote:
> 
> > On Mon, 22 Aug 2011 15:27:36 +1000
> > Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> [...]
> >> # 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
> > 
[...]
> 
> > Also, it doesn't immediately suggest to me a way of modifying method calls
> > (maybe __setattr__?). 
> 
> What do you mean, "modifying method calls"?

That was a rather badly-worded reference to a function in my original post which modified the action of list methods in ways specific to the new class. As I said, I re-read the docs on __getattr__, and now __setattr__, and I get what they do now.

Thanks for your pointers, I'll get back to work.

Regards,

John



More information about the Python-list mailing list