装饰器
从函数加功的角度切入
- 之前讲的都是由闭包的角度切入的,知识点会全部覆盖,但是可能不好理解装饰器有什么,下面是从函数加功的角度切入的,一步步简化成装饰器。
- 案例:从“”跟着一步步来,看装饰器是如何产生的。
import time
def computation_time0():
start_time = time.time()
time.sleep(2)
end_time = time.time()
run_time = (end_time - start_time) * 1000
print('程序一共运行了{}毫秒'.format(run_time))
my_fun()
第①步:产生需求。
- 看
####
包裹的部分,可不可改成其他函数,这样computation_time0
函数就变成了一个测试其他函数运行时间的功能函数了。
def computation_time1(every_fun):
start_time = time.time()
every_fun()
end_time = time.time()
run_time = (end_time - start_time) * 1000
print('程序一共运行了{}毫秒'.format(run_time))
def my_fun0():
print('我是my_fun0,一个普通函数,我先睡会儿')
time.sleep(2)
computation_time1(my_fun2)
第②步:改变调用思路。
- 能不能在调用
my_fun
的时候就自动实现计算时间的功能呢?要不每次都用功能函数很麻烦。 - 就好像圣斗士打架之前每次都需要先穿上圣衣,打完就脱了,现在实现穿一次后就不脱了。
def computation_time2(every_fun):
def new_every_fun():
start_time = time.time()
every_fun()
end_time = time.time()
run_time = (end_time - start_time) * 1000
print('程序一共运行了{}毫秒'.format(run_time))
return new_every_fun
my_fun2 = computation_time2(my_fun2)
my_fun2()
my_fun2()
第③步:简化调用。
- 利用
Python
中的装饰器语法糖——“@
”实现函数一出生就穿着“战甲”,根本不用去穿。
@computation_time2
def my_fun3():
print('我是my_fun3,一个普通的函数,从我出生就被穿上了计算运行时间的战甲')
time.sleep(2)
my_fun3()