30 装饰器终极版本(进阶)


def wrapper(func):     # 01 func--> f
def inner1(): #04
print("wrapper1,before func") #15
func() #16 f()
print("wrapper1,after func") #18
return inner1 #05

def wrapper2(func): #02 func--> inner1
def inner2(): #08
print("wrapper2,before func") #13
func() # 19 14 inner1()
print("wrapper2,atrer func")#20
return inner2 #09
@wrapper2 #10 07 f=wrapper2(f) ==wrapper2(inner1) ==inner2
@wrapper1 #06 03 f=wrapper1(f) ==inner1
def f(): # 11
print("in f")#17

f() # 12 inner2()21



import time

FLAGE = False
def timmer_out(flag):
def timmer(func):
def inner(*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 inner
return timmer
@timmer_out(FLAGE)
def wahaha():
time.sleep(0.1)
print("wahhhhahahahahh")
@timmer_out(FLAGE)
def erguotou():
time.sleep(0.1)
print("erguotoutoutotuou")
wahaha()
erguotou()

原文地址:https://www.cnblogs.com/wssaried/p/9916305.html