import time
def test_decorator():
time.sleep(1)
print("执行函数test_decorator")
如果按照刚才讲的方法,需要把函数修改成这样。
def test_decorator():
t1 = time.time()
time.sleep(1)
print("执行函数test_decorator")
t2 = time.time()
print("执行耗时" + str(t2 - t1))
def cost(func):
def warpper():
t1 = time.time()
res = func()
t2 = time.time()
print(func.__name__ + "执行耗时" + str(t2-t1))
return res
return warpper
cost
是一个函数,入参 func
是一个函数,
返回值 warpper
是一个函数, 使用非常简单。
def test_decorator():
time.sleep(1)
print("执行函数test_decorator")
输出结果为:
test = cost(test_decorator)
print(test)
test()
<function cost.<locals>.warpper at 0x7f4404ea9a80> 执行函数test_decorator test_decorator执行耗时1.0001599788665771
将 test_decorator
作为参数传给 cost
函数,cost
函数返回的 warpper
也是一个函数,
而这个函数里执行了 test_decorator
并且记录了函数的执行时间,对于 test_decorator
这个函数,
没有对它做任何改变,但却得到了它的执行时间。
上面的实例,并不是工作中使用的方法,创建了一个 test
变量,并将 cost
的返回值赋值给他,
是为了清晰的看到装饰器是如何工作的,装饰器的工作原理就是将被装饰的函数放入到一个新的函数中执行,
这个新的函数是自己编写的,因此,可以做任意想做的事情来实现自己想要的功能却不需要改变被装饰的函数。
实际工作中,这样使用装饰器:
@cost
def test_decorator():
time.sleep(1)
print("执行函数test_decorator")
test_decorator()
执行函数test_decorator test_decorator执行耗时1.0011086463928223
使用 @cost
装饰一个 test_decorator
等价于 test = cost(test_decorator)
,
好处时无需再定义一个变量 test
,当不需要记录函数的执行时间时,
只需要移除 @cost
即可。