How do I decorate an instance method with another class in Python 2.7?

久未见 提交于 2019-12-02 02:02:25

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>>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!