Replacing methods without subclassing

Aum spam-me at no-thanks.com
Sun Jan 26 03:25:52 EST 2003


Carl Banks wrote:

> Aum wrote:
>> Hi,
>> 
>> I notice that when I replace a method in a class instance, by doing:
>> 
>>        >>>myinstance.methodname = myfunc
>> 
>> the new function gets called *without* the class instance as the first
>> argument.
>> 
>> Is there any way of changing this *without* subclassing?
> 
> I can think of a few options:

<snip>

Thanks all the same, but some kind soul on OPN #python told me a much 
simpler way, which I post for benefit of others looking for similar.


import new
...

def setevhandler(self, func):
        """
        Assigns a new event handler function to the class (or subclass)
        instance. This provides an alternative to subclassing.
        """
        cls = self.__class__
        if type(func) is not types.FunctionType:
                raise MyNotFunctionError
        self.handleevent = new.instancemethod(func, self, cls)


Cheers
A





More information about the Python-list mailing list