当我为类方法创建装饰器时,它总是接收“function”类型的方法。
但是,当我稍微尝试一下时,我只得到了绑定(bind)方法:
class Test(object):
def save(self):
print "Save called"
def func(self):
print "Func called"
然后:
>>> type(Test.func)
<type 'instancemethod'>
>>> type(Test().func)
<type 'instancemethod'>
我最终想做的是创建一个类方法装饰器,它还装饰同一个类上的一些其他方法。我该如何去做呢?
最佳答案
这是不可能的;您必须使用类装饰器或元类来代替。装饰器语法
class Foo(object):
@dec
def bar(self): pass
表示
class Foo(object)
def bar(self): pass
bar = dec(bar)
其中 class
定义的处理方式如下:执行主体,然后收集定义并将它们包装在 class
对象中。即,装饰是在类
出现之前完成的。
关于python - 为什么 Python 类方法装饰器不接收该方法作为绑定(bind)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7484501/