How to add a Decorator to a Class Method

Jeff McNeil jeff at jmcneil.net
Tue Nov 20 00:22:47 EST 2007


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, gregpinero at gmail.com <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
>     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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20071120/eb38ecb3/attachment.html>


More information about the Python-list mailing list