【发布时间】:2014-05-31 20:40:45
【问题描述】:
在 Python 2.7 中,我想在类 Foo 中装饰一个实例方法 test,该装饰器也是一个名为 FooTestDecorator 的类。从用户 Chirstop 的 question 和 Python 2 文档的 Descriptor HowTo guide 我创建了这个示例。
但是似乎有一个问题,当我打印我的装饰方法对象时,它的(已检查?)名称是错误的,因为它被标记为像 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
你得到
<__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 中设置这些变量。为了简单起见,我没有把它放在示例中。
【问题讨论】:
标签: python class decorator python-decorators descriptor