How to add a Decorator to a Class Method

Arnaud Delobelle arnodel at googlemail.com
Tue Nov 20 07:57:24 CET 2007


On Nov 20, 4:59 am, "gregpin... at gmail.com" <gregpin... at gmail.com>
wrote:
> 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

'self' is not bound during class creation so self.pre does not exist.
Your decorator should be a regular function:

def pre(fn):
    ...

class A:
    @pre
    def func(self, x, y):
        ....

HTH

--
Arnaud




More information about the Python-list mailing list