Python装饰器
一、装饰器的定义
装饰器本质上就是一个python函数,他可以让其他函数在不需要做任何代码变动的前提下,增加额外的功能,装饰器的返回值也是一个函数对象。
装饰器的应用场景:比如插入日志,性能测试,事务处理,缓存等等场景。
简单版本的装饰器:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#简单的装饰器 def func(): print('小明') def timmer(f): def inner(): start_time = time.time() time.sleep(0.1) f() end_time = time.time() print('----> 执行效率%s' % (end_time - start_time)) return inner func = timmer(func) # inner func() # inner()
带语法糖版本的装饰器:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
语法糖 @ def timmer(f): def inner(): start_time = time.time() time.sleep(0.1) f() end_time = time.time() print('----> 执行效率%s' % (end_time - start_time)) return inner @timmer # func = timmer(func) def func(): print('小明') func() # inner()
带参数的装饰器:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#带参数的装饰器 def timmer(f): def inner(*args,**kwargs): start_time = time.time() time.sleep(0.1) f(*args,**kwargs) end_time = time.time() print('----> 执行效率%s' % (end_time - start_time)) return inner @timmer # func = timmer(func) def func(a): print('%s小明'%a) func('AAA')
带返回值的装饰器:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 带返回值的装饰器 def timmer(f): def inner(*args,**kwargs): start_time = time.time() time.sleep(0.1) ret = f(*args,**kwargs) # 222 end_time = time.time() print('----> 执行效率%s' % (end_time - start_time)) return ret return inner @timmer # func = timmer(func) def func(a): return 222 print(func('小明'))
通用装饰器:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#通用装饰器 def wrapper(func): def inner(*args,**kwargs): '''执行函数前操作''' ret = func(*args,**kwargs) '''执行函数后的操作''' return ret return inner @wrapper def func(): print(66) func()
带开关的装饰器:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import time flag = False def timmer_out(f): def timmer(func): def inner(*args,**kwargs): '''执行函数前操作''' if f: start_time = time.time() time.sleep(0.3) ret = func(*args,**kwargs) '''执行函数后操作''' end_time = time.time() print('执行效率%s'%(end_time - start_time)) return ret else: ret = func(*args,**kwargs) return ret return inner return timmer @timmer_out(flag) # 1, timmer_out(flag) 返回 timmer ---> def f1(): # 2, @timmer 就是你认识的装饰器 f1 = timmer(f1) print(666) @timmer_out(flag) # f2 = timmer(f2) def f2(): print(777) f1() f2()
多个装饰器装饰一个函数:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def wrapper1(func): # func = f def inner1(): print('wrapper1 ,before func') func() print('wrapper1 ,after func') return inner1 def wrapper2(func): # func = inner1 def inner2(): print('wrapper2 ,before func') func() print('wrapper2 ,after func') return inner2 @wrapper2 # f = wrapper2(f) 里面的f == inner1 外面的f = inner2 @wrapper1 # f = wrapper1(f) 返回inner1 f = inner1 def f(): print('in f') f() # inner2()