extending class

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Sep 23 09:17:53 EDT 2011

Andrea Crotti wrote:
> On 09/23/2011 10:31 AM, Peter Otten wrote:
>> 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
>> attributes
>> 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)
> Right thanks a lot it works perfectly.
> I don't like too much, however, to mess around in this way, maybe it's 
> better if I just fork the project
> and patch the original code.
> In this way maybe I can also contribute to it with patches (if they 
> are accepted)...
Did you consider subclassing your Var class ? This is how you extend a 
class behavior in OOP.

class PSIVar(var):
    def __init__(self, name, desc, other=None, fun=None):
        var.__init__(self, name, desc)
        if other is not None:
            self.other = other
            self.fun = fun
            assert callable(self.fun)

v1 = PSIVar('name', 'desc')

that's it.

By the way, don't create instance attribute conditionally. Your PSIVar 
instance should always have a 'other' attribute, its value can be None 


More information about the Python-list mailing list