Python中的裝飾器用于擴展可調用對象的功能,而無需修改其結構。基本上,裝飾器函數包裝另一個函數以增強或修改其行為。我們可以通過一個具體的例子了解基礎知識!讓我們編寫一個包含裝飾器實現示例的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’)
上面的裝飾器結構有助于我們在調用目標函數之前和之后在控制臺上顯示一些注釋。
以下是定義裝飾器的簡單步驟;
首先,我們應該定義一個可調用對象,例如裝飾器函數,其中還包含一個包裝器函數。
裝飾器函數應將目標函數作為參數。
并且它應該返回包裝函數,該包裝函數擴展了作為參數傳遞的目標函數。
包裝函數應包含目標函數調用以及擴展目標函數行為的代碼。
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僅在我們要裝飾的目標函數之前添加。然后,我們可以直接調用目標函數。就像我們在第一個實例中所做的那樣,無需顯式分配裝飾器。
定義多個裝飾器并使用參數裝飾函數
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’)
通過使用‘@’語法在目標函數之前添加多個裝飾器,可以輕松地用多個裝飾器裝飾目標函數。裝飾器的執行順序將與在目標函數之前列出的順序相同。
請注意,我們的目標函數中有一個參數loop。只要包裝函數使用相同的參數,就沒有問題。為了確保裝飾器可以靈活地接受任意數量的參數,將(* args,** kwargs)參數用于包裝函數。
重要要點
裝飾器定義可重用的代碼塊,您可以將這些代碼塊應用于可調用對象(函數,方法,類,對象),以修改或擴展其行為,而無需修改對象本身。
請考慮您的腳本中有許多函數執行許多不同的任務,并且需要向所有函數添加特定的行為。在這種情況下,將相同的代碼塊復制到函數中以具有所需的功能不是一個好的解決方案。您可以簡單地裝飾函數。
-
函數
+關注
關注
3文章
4346瀏覽量
63013 -
python
+關注
關注
56文章
4811瀏覽量
85075 -
調用
+關注
關注
0文章
8瀏覽量
3256
發布評論請先 登錄
相關推薦
Python Connector for InterBase連接解決方案
使用Python實現xgboost教程
適用于MySQL和MariaDB的Python連接器:可靠的MySQL數據連接器和數據庫
![適用于MySQL和MariaDB的<b class='flag-5'>Python</b>連接<b class='flag-5'>器</b>:可靠的MySQL數據連接<b class='flag-5'>器</b>和數據庫](https://file1.elecfans.com/web3/M00/06/57/wKgZPGeJ2kmAcWpWAAAh1ecL_LM122.png)
Python中代理服務器的配置與應用
使用Python構建高效的HTTP代理服務器
【每天學點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的關系是什么
opencv-python和opencv一樣嗎
用pycharm進行python爬蟲的步驟
如何用python調用瀏覽器的視頻?
鴻蒙OS開發實例:【ArkTS類庫多線程@Concurrent裝飾器校驗并發函數】
![鴻蒙OS開發實例:【ArkTS類庫多線程@Concurrent<b class='flag-5'>裝飾</b><b class='flag-5'>器</b>校驗并發函數】](https://file1.elecfans.com/web2/M00/C5/D1/wKgZomYChGOAUaiiAADe1d8SeRY102.jpg)
評論