1、說明
裝飾本質上是一個Python函數,它能使其他函數在沒有任何代碼變化的情況下增加額外的功能。有了裝飾,我們可以抽出大量與函數功能無關的相同代碼,繼續重用。
2、應用場景
包括插入日志、性能測試、事務處理、緩存和權限驗證。
3、實例
# 裝飾器
# func指函數
def decorator(func):
def wrapper(*args, **kwargs):
# 執行函數內部邏輯 打印時間
print(time.time(), args, kwargs)
# 執行調用函數中邏輯 打印不同參數
func(*args, **kwargs)
return wrapper
# 一個參數
@decorator
def function(param):
print('function : this is decorator ' + param)
# 兩個參數
@decorator
def function1(param1, param2):
print('function1 : this is decorator ' + param1)
print('function1 : this is decorator ' + param2)
# 三個參數(可變參數)
@decorator
def function2(param1, param2, **kwargs):
print('function2 : this is decorator ' + param1)
print('function2 : this is decorator ' + param2)
print(kwargs)
function('param')
function1('param1' , 'param2')
function2('param1' , 'param2', x=1,y=2,z=3)
內容擴展:
函數注冊表
簡單注冊表
funcs = []
def register(func):
funcs.append(func)
return func
@register
def a():
return 3
@register
def b():
return 5
# 訪問結果
result = [func() for func in funcs]
注冊表隔離(使用類的不同實例)
class Registry(object):
def __init__(self):
self._funcs = []
def register(self, func):
self._funcs.append(func)
def run_all(self):
return [func() for func in self._funcs]
r1 = Registry()
r2 = Registry()
@r1.register
def a():
return 3
@r2.register
def b():
return 5
@r1.register
@r2.register
到此這篇關于Python裝飾器的應用場景及實例用法的文章就介紹到這了,更多相關Python裝飾器的應用場景內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- 詳解Python裝飾器之@property
- python 裝飾器的使用與要點
- python高級語法之閉包和裝飾器詳解
- Python pytest裝飾器總結(實例詳解)
- python基礎之裝飾器詳解
- Python 的lru_cache裝飾器使用簡介
- Python 中@lazyprop 裝飾器的用法