且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python 2.7中用另一个类装饰一个实例方法?

更新时间:2022-06-14 06:23:16

您的装饰器实例没有 __name __ 属性,因此Python与问号相关。

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

使用 functools.update_wrapper() 复制函数名称一些其他有趣的特殊属性(如docstring,函数模块名称以及函数可能具有的任何自定义属性):

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)

演示:

>>> 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>>