How to add a Decorator to a Class Method
davisn90210 at gmail.com
davisn90210 at gmail.com
Tue Nov 20 13:57:46 EST 2007
On Nov 20, 12:32 pm, "gregpin... at gmail.com" <gregpin... at gmail.com>
wrote:
> On Nov 20, 2:05 am, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
>
>
>
> > On Mon, 19 Nov 2007 20:59:51 -0800, 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
>
> > 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 `... at 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
>
> Thanks those answers make sense. But for this function if defined
> outside the class:
>
> > def pre(fn):
> > def new_func(*args, **kwargs):
> > print "'hi'"
> > fn(*args, **kwargs)
> > return new_func
>
> Can new_func reference self? Would self just be one of the args?
>
> -Greg
For methods, self is always "just one of the args". When the
decorator is applied to a method, self will be args[0] in new_func.
--Nathan Davis
More information about the Python-list
mailing list