How to add a Decorator to a Class Method

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Tue Nov 20 02:05:02 EST 2007


On Mon, 19 Nov 2007 20:59:51 -0800, gregpinero 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

At this point there is no `self` which is exactly what the exception says
if you run this. This method definition executed at class definition time
so there is no instance of `A`.  You can't change it to ``@A.pre`` either
because the class is not fully constructed yet so the class name `A` does
not exist yet.  So you have to move `pre()` out of the class.

def pre(fn):
    def new_func(*args, **kwargs):
        print "'hi'"
        fn(*args, **kwargs)
    return new_func

class A(object):
    @pre
    def func(self, a, b):
        print a + b

a = A()
a.func(3, 5)

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list