装饰器原则
1. 不能修改被装饰函数的源代码
2. 不能修改被装饰函数的调用方式
import time
def timer(func): # func = test1、test2
def deco(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs) # test1、test2 本身在这里运行
stop_time = time.time()
print('Running time:%s' % (stop_time - start_time)) # 并输出装饰器带来的额外功能,结束。
return deco
@timer # 1. 即 test1 = timer(test1),调用了timer,把返回值 deco 传给 test1,并把 test1 作为参数传给 func
def test1():
time.sleep(3)
print('In the test1')
@timer
def test2(name, age):
time.sleep(2)
print('In the test2', name, age)
test1() # 2. 调用 test1 相当于调用 deco,直接跳到 timer 里的 deco,开始运行 deco 里的内容
test2("Lief", 20)