有参装饰器
def timmerout(flag1): #flag1 =flag
def timmer(f):
def inner(*args,**kwargs):
if flag1:
start_time = time.time()
ret = f(*args,**kwargs)
end_time = time.time()
print('此函数的执行效率%s' % (end_time - start_time))
return ret
else:
ret = f(*args, **kwargs)
return ret
return inner
return timmer
flag = False
@timmerout(flag) #将@与timmerout(flag)分离,拿到后者的执行结果后在与@组合。
def func1():
time.sleep(0.3)
print('非常复杂......')
return 666
1,将@ 与函数分开@ timmerout(flag) 返回了timmer
2,将@timmer结合
PS:遇到问题没人解答?需要Python学习资料?可以加点击下方链接自行获取
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76
多个装饰器装饰一个函数
def wrapper1(func): # func = f函数名
def inner1():
print('wrapper1 ,before func') # 2
func() # f函数名()
print('wrapper1 ,after func') # 4
return inner1
def wrapper2(func): # func = inner1
def inner2():
print('wrapper2 ,before func') # 1
func() # inner1()
print('wrapper2 ,after func') # 5
return inner2
@wrapper2 # f = warpper2(f) 里面的f是inner1 外面的f是inner2
@wrapper1 # f = warpper1(f) 里面的f函数名 外面的f 是inner1
def f():
print('in f') # 3
f() # inner2()
# wrapper2 ,before func
# wrapper1 ,before func
# in f
# wrapper1 ,after func
# wrapper2 ,after func