Python中的裝飾器用于擴展可調(diào)用對象的功能,而無需修改其結(jié)構(gòu)。基本上,裝飾器函數(shù)包裝另一個函數(shù)以增強或修改其行為。我們可以通過一個具體的例子了解基礎(chǔ)知識!讓我們編寫一個包含裝飾器實現(xiàn)示例的Python3代碼:
裝飾定義
defdecorator_func_logger(target_func):defwrapper_func():print(“Before calling”, target_func.__name__) target_func() print(“After calling”, target_func.__name__)return wrapper_funcdef target(): print(‘Python is in the decorated target function’)dec_func = decorator_func_logger(target)dec_func()Output:air-MacBook-Air:$ python DecoratorsExample.py(‘Before calling’, ‘target’)Python isin the decorated target function(‘After calling’, ‘target’)
上面的裝飾器結(jié)構(gòu)有助于我們在調(diào)用目標函數(shù)之前和之后在控制臺上顯示一些注釋。
以下是定義裝飾器的簡單步驟;
首先,我們應(yīng)該定義一個可調(diào)用對象,例如裝飾器函數(shù),其中還包含一個包裝器函數(shù)。
裝飾器函數(shù)應(yīng)將目標函數(shù)作為參數(shù)。
并且它應(yīng)該返回包裝函數(shù),該包裝函數(shù)擴展了作為參數(shù)傳遞的目標函數(shù)。
包裝函數(shù)應(yīng)包含目標函數(shù)調(diào)用以及擴展目標函數(shù)行為的代碼。
defdecorator_func_logger(target_func):defwrapper_func(): print(“Before calling”, target_func.__name__) target_func() print(“After calling”, target_func.__name__)return wrapper_func@decorator_func_loggerdef target():print(‘Python is in the decorated target function’)target()Output:air-MacBook-Air:$ python DecoratorsExample.py(‘Before calling’, ‘target’)Python isin the decorated target function(‘After calling’, ‘target’)
借助Python提供的語法糖,我們可以簡化裝飾器的定義,如上所示。
請注意,@ decorator_func_logger僅在我們要裝飾的目標函數(shù)之前添加。然后,我們可以直接調(diào)用目標函數(shù)。就像我們在第一個實例中所做的那樣,無需顯式分配裝飾器。
定義多個裝飾器并使用參數(shù)裝飾函數(shù)
import timedef decorator_func_logger(target_func):defwrapper_func(*args, **kwargs):print(“Before calling”, target_func.__name__) target_func(*args, **kwargs)print(“After calling”, target_func.__name__)return wrapper_funcdef decorator_func_timeit(target_func):defwrapper_func(*args, **kwargs): ts = time.time() target_func(*args, **kwargs) te = time.time()print (target_func.__name__, (te - ts) * 1000)return wrapper_func@decorator_func_logger@decorator_func_timeitdef target(loop): count = 0 print(‘Python is in the decorated target function’)for number in range(loop): count += numbertarget(100)target(3000)Output:air-MacBook-Air:$ python DecoratorsExample.py(‘Before calling’, ‘wrapper_func’)Python isin the decorated target function(‘target’, 0.015974044799804688)(‘After calling’, ‘wrapper_func’)(‘Before calling’, ‘wrapper_func’)Python isin the decorated target function(‘target’, 0.47397613525390625)(‘After calling’, ‘wrapper_func’)
通過使用‘@’語法在目標函數(shù)之前添加多個裝飾器,可以輕松地用多個裝飾器裝飾目標函數(shù)。裝飾器的執(zhí)行順序?qū)⑴c在目標函數(shù)之前列出的順序相同。
請注意,我們的目標函數(shù)中有一個參數(shù)loop。只要包裝函數(shù)使用相同的參數(shù),就沒有問題。為了確保裝飾器可以靈活地接受任意數(shù)量的參數(shù),將(* args,** kwargs)參數(shù)用于包裝函數(shù)。
重要要點
裝飾器定義可重用的代碼塊,您可以將這些代碼塊應(yīng)用于可調(diào)用對象(函數(shù),方法,類,對象),以修改或擴展其行為,而無需修改對象本身。
請考慮您的腳本中有許多函數(shù)執(zhí)行許多不同的任務(wù),并且需要向所有函數(shù)添加特定的行為。在這種情況下,將相同的代碼塊復(fù)制到函數(shù)中以具有所需的功能不是一個好的解決方案。您可以簡單地裝飾函數(shù)。
-
函數(shù)
+關(guān)注
關(guān)注
3文章
4346瀏覽量
62974 -
python
+關(guān)注
關(guān)注
56文章
4807瀏覽量
85040 -
調(diào)用
+關(guān)注
關(guān)注
0文章
8瀏覽量
3255
發(fā)布評論請先 登錄
相關(guān)推薦
Python Connector for InterBase連接解決方案
使用Python實現(xiàn)xgboost教程
適用于MySQL和MariaDB的Python連接器:可靠的MySQL數(shù)據(jù)連接器和數(shù)據(jù)庫
![適用于MySQL和MariaDB的<b class='flag-5'>Python</b>連接<b class='flag-5'>器</b>:可靠的MySQL數(shù)據(jù)連接<b class='flag-5'>器</b>和數(shù)據(jù)庫](https://file1.elecfans.com/web3/M00/06/57/wKgZPGeJ2kmAcWpWAAAh1ecL_LM122.png)
Python中代理服務(wù)器的配置與應(yīng)用
使用Python構(gòu)建高效的HTTP代理服務(wù)器
【每天學點AI】一個例子帶你了解Python裝飾器到底在干嘛!
![【每天學點AI】一個例子帶你了解<b class='flag-5'>Python</b><b class='flag-5'>裝飾</b><b class='flag-5'>器</b>到底在干嘛!](https://file1.elecfans.com/web2/M00/08/0A/wKgaombtODuAOOmCAAAo9ZITeps802.png)
pytorch和python的關(guān)系是什么
Python中變量在內(nèi)存中的存儲方式
opencv-python和opencv一樣嗎
用pycharm進行python爬蟲的步驟
如何用python調(diào)用瀏覽器的視頻?
鴻蒙OS開發(fā)實例:【ArkTS類庫多線程@Concurrent裝飾器校驗并發(fā)函數(shù)】
![鴻蒙OS開發(fā)實例:【ArkTS類庫多線程@Concurrent<b class='flag-5'>裝飾</b><b class='flag-5'>器</b>校驗并發(fā)函數(shù)】](https://file1.elecfans.com/web2/M00/C5/D1/wKgZomYChGOAUaiiAADe1d8SeRY102.jpg)
鴻蒙原生應(yīng)用開發(fā)-ArkTS語言基礎(chǔ)類庫多線程@Concurrent裝飾器校驗并發(fā)函數(shù)
基于Python的地圖繪制教程
![基于<b class='flag-5'>Python</b>的地圖繪制教程](https://file1.elecfans.com/web2/M00/C0/F4/wKgZomXb72KADq8JAABAFRaefm0918.png)
評論