Think about the context in which your function definition is executed and
how the 'self' parameter is implemented.   Your definitions (and decorator
calls) are executed in the context of 'class A.'

That said, the following would work:

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

>>> A().func(1,2)
hi
3
>>>


On 11/19/07, [EMAIL PROTECTED] <[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
>     def func(self,a,b):
>         print a+b
>
> Should result in:
> >>> a = A()
> >>> a.func(3,5)
> 'hi'
> 8
>
> Thanks,
>
> -Greg
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to