On Nov 20, 2:05 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Mon, 19 Nov 2007 20:59:51 -0800, [EMAIL PROTECTED] 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 [EMAIL PROTECTED] 
> 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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to