How to wrap a class's methods?

Grant Edwards grante at visi.com
Thu Feb 17 15:22:45 EST 2005


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.

-- 
Grant Edwards                   grante             Yow!  Wait... is this a FUN
                                  at               THING or the END of LIFE in
                               visi.com            Petticoat Junction??



More information about the Python-list mailing list