extending class

Peter Otten __peter__ at web.de
Fri Sep 23 05:31:30 EDT 2011

Andrea Crotti wrote:

> I wanted to add a couple of parameters to a class from a given library
> (paste-script), but without changing the original code.
> So I thought, I create a wrapper class which adds what I need, and then
> dispatch all the calls to the super class.
> My following attempt gives, however, a recursion error, but why?

Inside __getattribute__() you ask for self.first_var which triggers another 
__getattribute__() call that once again trys to determine the first_var 
attribute before it returns...

Try using __getattr__() instead which is only triggered for non-existent 

def __getattr__(self, name):
    return getattr(self.first_var, name)

or check for the attributes you don't want to delegate explicitly:

def __getattribute__(self, name):
    if name == "first_var":
        return super(PSIVar, self).__getattribute__(name)
    return getattr(self.first_var, name)

> class PSIVar(object):
>      """Extend var implementation from the paste-script, to add the
>      ability of correlating variables
>  >>> v = var("name", "desc")
>  >>> v.name == 'name'
>      True
>  >>> v1 = PSIVar(v)
>  >>> v1.name == 'name'
>      True
>      """
>      def __init__(self, first_var, other=None, fun=None):
>          # this is of type defined there
>          self.first_var = first_var
>          if other is not None:
>              self.other = other
>              self.fun = fun
>              assert callable(self.fun)
>      # now try to dispatch every method call to the other class
>      # must probably call the super class
>      def __getattribute__(self, attr):
>          return self.first_var.__getattribute__(attr)

More information about the Python-list mailing list