Adding modified methods from another class without subclassing

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Aug 23 05:26:30 CEST 2011


On Tue, 23 Aug 2011 10:55 am John O'Hagan 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
>> 
> [..]
>> 
>> 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.

Which is what the call to super will accomplish, but if the behaviour ever
changes (including the error message given), you won't have to change your
class.



-- 
Steven




More information about the Python-list mailing list