Python全系列 教程
3567个小节阅读:5931.1k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
有时候,我们需要多个装饰器修饰一个函数。比如:需要增加日志功能、增加执行效率测试功能。
装饰器函数的执行顺序是分为(被装饰函数)定义阶段和(被装饰函数)执行阶段的,装饰器函数在被装饰函数定义好后立即执行
【示例】多个装饰器执行顺序
xxxxxxxxxx
@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()
【示例】增加日志和执行计时功能的装饰器
xxxxxxxxxx
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()
实时效果反馈
1. 如下关于多个装饰器修饰一个函数fun2()
,说法错误的是:
xxxxxxxxxx
@mylog
@cost_time
#函数定义阶段
def fun2():
print("使用功能2")
#函数调用阶段
fun2()
A 函数定义阶段:先执行mylog、再执行cost_time
B 函数调用阶段:先执行mylog的内部函数、再执行cost_time的内部函数
C 函数定义阶段:先执行cost_time、再执行mylog
答案
1=>A