python中的装饰器
装饰器的基本使用。
import time# 普通写法def CountTime(func):print("开始运行程序....")start = time.time()func()end = time.time()print("程序运行结束....")print(end-start)def myfunc():time.sleep(2)print("Hello World")CountTime(myfunc)# 使用装饰器的写法def CountTimeTwo(func):def Count():print("开始运行程序....")start = time.time()func()end = time.time()print("程序运行结束....")print(end-start)return Count@CountTimeTwodef myfuncTwo():time.sleep(2)print("Hello World")myfuncTwo()
多个装饰器可以作用在同一函数上。
给装饰器传递参数。
import time# 带参数的装饰器def logger(msg):def CountTime(func):def Count():print(f"开始运行{msg}程序....")start = time.time()func()end = time.time()print("程序运行结束....")print(end-start)return Countreturn CountTime@logger(msg="A")def myfuncThree():time.sleep(2)print("Hello World,装饰器嵌套。")myfuncThree()
