标签:**kwargs end time() outer imm class http 技术 div
只用在装饰器最外层嵌套一个即可,以达到轻易控制装饰器函数是否执行的作用
import time flag = False def timmer_outer(flag): def timmer(func): def innner(*args,**kwargs): if flag: start = time.time() ret = func(*args,**kwargs) end = time.time() print(end-start) return ret else: ret = func(*args, **kwargs) return ret return innner return timmer #执行步骤:两步(timmer_outer(flag)执行后返回timmer,再执行@tmmer) @timmer_outer(flag) def func1(): time.sleep(0.1) print("函数1") @timmer_outer(flag) def func2(): time.sleep(0.1) print("函数2") func1() func2()
def wrapper1(func):#func-->f def inner1(): print("wrapper1,before f") ret = func() func() #f() print("wrapper1,after f ") return ret return inner1 def wrapper2(func): def inner2(): print("wrapper2,before f") ret = func() func() #inner1() print("wrapper2,after f ") return ret return inner2 #f=wrapper2(f) = f=wrapper2(inner1) = inner2 @wrapper2 # f=wrapper1(f) = inner1 @wrapper1 def f(): print("in f") return ‘娃哈哈‘ print(f())
结果:
wrapper2,before f
wrapper1,before f
in f
wrapper1,after f
wrapper2,after f
娃哈哈
10-5装饰器进阶_带参数的装饰器、多个装饰器装饰同一个函数
标签:**kwargs end time() outer imm class http 技术 div
原文地址:https://www.cnblogs.com/Cheryol/p/9745082.html