在Python 2.7中我想装饰一个实例方法test
在班上Foo
带有一个装饰器,它也是一个名为FooTestDecorator
。来自用户 Chirstop 的question和 Python 2 文档'描述符操作指南我创建了这个例子。
然而,似乎有一个问题,当我打印我的装饰方法对象时,它的(检查?)名称是错误的,因为它被标记为问号,例如Foo.?
.
import types
class FooTestDecorator(object):
def __init__(self,func):
self.func=func
self.count=0
# tried self.func_name = func.func_name, but seemed to have no effect
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)
class Foo:
@FooTestDecorator
def test(self,a):
print a
def bar(self,b):
print b
如果你测试它:
f=Foo()
print Foo.__dict__['test']
print Foo.test
print f.test
print Foo.__dict__['bar']
print Foo.bar
print f.bar
you get
<__main__.FooTestDecorator ...object...>
<unbound method Foo.?>
<bound method Foo.? of ...instance...>
<function bar at 0x...>
<unbound method Foo.bar>
<bound method Foo.bar of ...instance...>
可以看到替换方法如图Foo.?
。这似乎是错误的。
如何获得正确的类装饰实例方法?
注意:我的原因是我想使用来自FooDecorator
实例的self
我会在 init 中设置它。为了简单起见,我没有将其放在示例中。