How to wrap a class's methods?
Michael Spencer
mahs at telcopartners.com
Thu Feb 17 16:04:51 EST 2005
Grant Edwards wrote:
> On 2005-02-17, Steven Bethard <steven.bethard at gmail.com> wrote:
>
>
>>py> class C(object):
>>... def f(self, *args):
>>... print "f:", args
>>... def g(self, *args):
>>... print "g:", args
>>...
>>py> class D(C):
>>... pass
>>...
>>py> class Wrapper(object):
>>... def __init__(self, func):
>>... self.func = func
>>... def __call__(self, *args):
>>... print "wrapped"
>>... return self.func(*args)
>>...
>>py> for name in ['f', 'g']:
>>... wrapper = Wrapper(getattr(C, name))
>>... setattr(D, name, new.instancemethod(wrapper, None, D))
>
>
> Thanks. The stuff provided by the "new" module is what I was
> missing.
>
No magic in the 'new' module - new.instancemethod is just a synonym for the
method type:
>>> import new, types
>>> new.instancemethod is types.MethodType
True
Michael
More information about the Python-list
mailing list