Skip to content Skip to sidebar Skip to footer

How Do I Decorate An Instance Method With Another Class In Python 2.7?

In Python 2.7 I'd like to decorate an instance method test in class Foo with a decorator that is also a class called FooTestDecorator. From user Chirstop's question and the Python

Solution 1:

Your decorator instance has no __name__ attribute, so Python has to do with a question mark instead.

Use functools.update_wrapper() to copy over the function name, plus a few other interesting special attributes (such as the docstring, the function module name and any custom attributes the function may have):

import types
from functools import update_wrapper

class FooTestDecorator(object):
    def __init__(self,func):
        self.func=func
        self.count=0
        update_wrapper(self, func)

    def __get__(self,obj,objtype=None):
        return types.MethodType(self,obj,objtype)
    def __call__(self,*args,**kwargs):
        self.count+=1
        return self.func(*args,**kwargs)

Demo:

>>> f=Foo()
>>> print Foo.__dict__['test']
<__main__.FooTestDecorator object at 0x11077e210>
>>> print Foo.test
<unbound method Foo.test>
>>> print f.test
<bound method Foo.test of <__main__.Foo instance at 0x11077a830>>

Post a Comment for "How Do I Decorate An Instance Method With Another Class In Python 2.7?"