How to mix-in __getattr__ after the fact?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Nov 8 00:58:17 EST 2011


On Tue, 08 Nov 2011 15:17:14 +1100, Lie Ryan wrote:

> On 10/31/2011 11:01 PM, dhyams wrote:
>>
>> Thanks for all of the responses; everyone was exactly correct, and
>> obeying the binding rules for special methods did work in the example
>> above.  Unfortunately, I only have read-only access to the class itself
>> (it was a VTK class wrapped with SWIG), so I had to find another way to
>> accomplish what I was after.
>>
>>
> As a big huge hack, you can always write a wrapper class:
> 
> class Wrapper(object):
>      def __init__(self, *args, **kwargs):
>          self.__object = MySWIGClass(*args, **kwargs)
>      def __getattr__(self, attr):
>          try:
>              return getattr(self.__object, attr)
>          except AttributeError:
>              ...


That's not a hack, that's a well-respected design pattern called 
Delegation.

http://rosettacode.org/wiki/Delegate
http://en.wikipedia.org/wiki/Delegation_pattern


In this case, you've implemented about half of automatic delegation:

http://code.activestate.com/recipes/52295

which used to be much more important in Python prior to the type/class 
unification in version 2.2.


To also delegate special dunder methods using new-style classes, see this:

http://code.activestate.com/recipes/252151



-- 
Steven



More information about the Python-list mailing list