【发布时间】:2019-02-03 03:28:42
【问题描述】:
考虑这个小例子:
import datetime as dt
class Timed(object):
def __init__(self, f):
self.func = f
def __call__(self, *args, **kwargs):
start = dt.datetime.now()
ret = self.func(*args, **kwargs)
time = dt.datetime.now() - start
ret["time"] = time
return ret
class Test(object):
def __init__(self):
super(Test, self).__init__()
@Timed
def decorated(self, *args, **kwargs):
print(self)
print(args)
print(kwargs)
return dict()
def call_deco(self):
self.decorated("Hello", world="World")
if __name__ == "__main__":
t = Test()
ret = t.call_deco()
打印出来的
Hello
()
{'world': 'World'}
为什么self 参数(应该是Test obj 实例)没有作为第一个参数传递给装饰函数decorated?
如果我手动操作,例如:
def call_deco(self):
self.decorated(self, "Hello", world="World")
它按预期工作。但是如果我必须提前知道一个函数是否被装饰,它就违背了装饰器的全部目的。这里的模式是什么,还是我误解了什么?
【问题讨论】:
-
快速谷歌搜索:thecodeship.com/patterns/guide-to-python-function-decorators(参见“装饰方法”部分)
-
当你使用函数作为装饰器而不是可调用对象时,你不会遇到这种问题。
标签: python class self python-decorators