How to add a Decorator to a Class Method

gregpinero at gmail.com gregpinero at gmail.com
Tue Nov 20 05:59:51 CET 2007


How do I add a decorator to a class method?  Here's what I want to do,
but I guess my syntax isn't right.  Any advice?

class A:
    def pre(self,fn):
        def new_func(*args,**kwargs):
            print 'hi'
            fn(*args,**kwargs)
        return new_func
    @self.pre
    def func(self,a,b):
        print a+b

Should result in:
>>> a = A()
>>> a.func(3,5)
'hi'
8

Thanks,

-Greg



More information about the Python-list mailing list