二 多个装饰器_执行顺序的深刻剖析
多个装饰器
有时候,我们需要多个装饰器修饰一个函数。比如:需要增加日志功能、增加执行效率测试功能。
装饰器函数的执行顺序是分为(被装饰函数)定义阶段和(被装饰函数)执行阶段的,装饰器函数在被装饰函数定义好后立即执行
- 在函数定义阶段:执行顺序是从最靠近函数的装饰器开始,自内而外的执行
- 在函数执行阶段:执行顺序由外而内,一层层执行
【示例】多个装饰器执行顺序
@mylog @cost_time # 函数定义阶段: # 相当于: # fun2 = cost_time(fun2) # fun2 = mylog(fun2) # 也相当于: # fun2 = mylog(cost_time(fun2)) # 定义阶段:先执行cost_time函数,再执行mylog函数 def fun2(): pass #调用执行阶段 #先执行mylog的内部函数,再执行cost_time的内部函数 fun2()
【示例】增加日志和执行计时功能的装饰器
import time
def mylog(func):
print("mylog start")
def infunc():
print("日志纪录 start")
func()
print("日志纪录 end")
print("mylog end")
return infunc
def cost_time(func):
print("cost time start")
def infunc():
print("开始计时..")
start = time.time()
func()
end = time.time()
print(f"耗费时间:{end-start}")
return end-start
print("cost time end")
return infunc
@mylog
@cost_time
# 相当于:
# fun2 = cost_time(fun2)
# fun2 = mylog(fun2)
# 也相当于:
# fun2 = mylog(cost_time(fun2))
def fun2():
print("使用功能2")
time.sleep(2)
print("使用功能22")
fun2()