
- Python 基礎
- Python - 首頁
- Python - 概述
- Python - 歷史
- Python - 特性
- Python vs C++
- Python - Hello World 程式
- Python - 應用領域
- Python - 直譯器
- Python - 環境搭建
- Python - 虛擬環境
- Python - 基本語法
- Python - 變數
- Python - 資料型別
- Python - 型別轉換
- Python - Unicode 系統
- Python - 字面量
- Python - 運算子
- Python - 算術運算子
- Python - 比較運算子
- Python - 賦值運算子
- Python - 邏輯運算子
- Python - 位運算子
- Python - 成員運算子
- Python - 身份運算子
- Python - 運算子優先順序
- Python - 註釋
- Python - 使用者輸入
- Python - 數字
- Python - 布林值
- Python 控制語句
- Python - 控制流
- Python - 決策
- Python - if 語句
- Python - if else
- Python - 巢狀 if
- Python - match-case 語句
- Python - 迴圈
- Python - for 迴圈
- Python - for-else 迴圈
- Python - while 迴圈
- Python - break 語句
- Python - continue 語句
- Python - pass 語句
- Python - 巢狀迴圈
- Python 函式 & 模組
- Python - 函式
- Python - 預設引數
- Python - 關鍵字引數
- Python - 僅限關鍵字引數
- Python - 位置引數
- Python - 僅限位置引數
- Python - 可變引數
- Python - 變數作用域
- Python - 函式註解
- Python - 模組
- Python - 內建函式
- Python 字串
- Python - 字串
- Python - 字串切片
- Python - 修改字串
- Python - 字串連線
- Python - 字串格式化
- Python - 跳脫字元
- Python - 字串方法
- Python - 字串練習
- Python 列表
- Python - 列表
- Python - 訪問列表元素
- Python - 修改列表元素
- Python - 新增列表元素
- Python - 刪除列表元素
- Python - 遍歷列表
- Python - 列表推導式
- Python - 列表排序
- Python - 複製列表
- Python - 合併列表
- Python - 列表方法
- Python - 列表練習
- Python 元組
- Python - 元組
- Python - 訪問元組元素
- Python - 更新元組
- Python - 解包元組
- Python - 遍歷元組
- Python - 合併元組
- Python - 元組方法
- Python - 元組練習
- Python 集合
- Python - 集合
- Python - 訪問集合元素
- Python - 新增集合元素
- Python - 刪除集合元素
- Python - 遍歷集合
- Python - 合併集合
- Python - 複製集合
- Python - 集合運算子
- Python - 集合方法
- Python - 集合練習
- Python 字典
- Python - 字典
- Python - 訪問字典元素
- Python - 修改字典元素
- Python - 新增字典元素
- Python - 刪除字典元素
- Python - 字典檢視物件
- Python - 遍歷字典
- Python - 複製字典
- Python - 巢狀字典
- Python - 字典方法
- Python - 字典練習
- Python 陣列
- Python - 陣列
- Python - 訪問陣列元素
- Python - 新增陣列元素
- Python - 刪除陣列元素
- Python - 遍歷陣列
- Python - 複製陣列
- Python - 反轉陣列
- Python - 排序陣列
- Python - 合併陣列
- Python - 陣列方法
- Python - 陣列練習
- Python 檔案處理
- Python - 檔案處理
- Python - 寫入檔案
- Python - 讀取檔案
- Python - 重新命名和刪除檔案
- Python - 目錄
- Python - 檔案方法
- Python - OS 檔案/目錄方法
- Python - OS 路徑方法
- 面向物件程式設計
- Python - OOPs 概念
- Python - 類 & 物件
- Python - 類屬性
- Python - 類方法
- Python - 靜態方法
- Python - 建構函式
- Python - 訪問修飾符
- Python - 繼承
- Python - 多型
- Python - 方法重寫
- Python - 方法過載
- Python - 動態繫結
- Python - 動態型別
- Python - 抽象
- Python - 封裝
- Python - 介面
- Python - 包
- Python - 內部類
- Python - 匿名類和物件
- Python - 單例類
- Python - 包裝類
- Python - 列舉
- Python - 反射
- Python 錯誤 & 異常
- Python - 語法錯誤
- Python - 異常
- Python - try-except 塊
- Python - try-finally 塊
- Python - 丟擲異常
- Python - 異常鏈
- Python - 巢狀 try 塊
- Python - 使用者自定義異常
- Python - 日誌
- Python - 斷言
- Python - 內建異常
- Python 多執行緒
- Python - 多執行緒
- Python - 執行緒生命週期
- Python - 建立執行緒
- Python - 啟動執行緒
- Python - 加入執行緒
- Python - 執行緒命名
- Python - 執行緒排程
- Python - 執行緒池
- Python - 主執行緒
- Python - 執行緒優先順序
- Python - 守護執行緒
- Python - 執行緒同步
- Python 同步
- Python - 執行緒間通訊
- Python - 執行緒死鎖
- Python - 中斷執行緒
- Python 網路程式設計
- Python - 網路程式設計
- Python - Socket 程式設計
- Python - URL 處理
- Python - 泛型
- Python 庫
- NumPy 教程
- Pandas 教程
- SciPy 教程
- Matplotlib 教程
- Django 教程
- OpenCV 教程
- Python 其他
- Python - 日期 & 時間
- Python - 數學
- Python - 迭代器
- Python - 生成器
- Python - 閉包
- Python - 裝飾器
- Python - 遞迴
- Python - 正則表示式
- Python - PIP
- Python - 資料庫訪問
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 輸出格式化
- Python - 效能測量
- Python - 資料壓縮
- Python - CGI 程式設計
- Python - XML 處理
- Python - GUI 程式設計
- Python - 命令列引數
- Python - 文件字串
- Python - JSON
- Python - 傳送郵件
- Python - 擴充套件
- Python - 工具/實用程式
- Python - GUIs
- Python 高階概念
- Python - 抽象基類
- Python - 自定義異常
- Python - 高階函式
- Python - 物件內部
- Python - 記憶體管理
- Python - 元類
- Python - 使用元類進行超程式設計
- Python - 模擬和存根
- Python - Monkey Patching
- Python - 訊號處理
- Python - 型別提示
- Python - 自動化教程
- Python - Humanize 包
- Python - 上下文管理器
- Python - 協程
- Python - 描述符
- Python - 診斷和修復記憶體洩漏
- Python - 不可變資料結構
- Python 有用資源
- Python - 問答
- Python - 線上測試
- Python - 快速指南
- Python - 參考
- Python - 速查表
- Python - 專案
- Python - 有用資源
- Python - 討論
- Python 編譯器
- NumPy 編譯器
- Matplotlib 編譯器
- SciPy 編譯器
Python - 裝飾器
在 Python 中,裝飾器是一個函式,它接收另一個函式作為引數。被裝飾的函式就是作為引數傳入的函式。裝飾器可以擴充套件引數函式的行為,而無需實際修改它。
在本章中,我們將學習如何使用 Python 裝飾器。
定義函式裝飾器
Python 中的函式是一等公民。這意味著它可以像其他資料型別(如數字、字串或列表等)一樣作為引數傳遞給另一個函式。也可以在一個函式內部定義另一個函式。這樣的函式稱為巢狀函式。此外,函式也可以返回其他函式。
裝飾器函式的典型定義如下:
def decorator(arg_function): #arg_function to be decorated def nested_function(): #this wraps the arg_function and extends its behaviour #call arg_function arg_function() return nested_function
這是一個普通的 Python 函式:
def function(): print ("hello")
現在可以透過將其傳遞給裝飾器來裝飾此函式以擴充套件其行為:
function=decorator(function)
如果現在執行此函式,則將顯示由裝飾器擴充套件的輸出。
Python 裝飾器的示例
練習以下示例以理解 Python 裝飾器的概念:
示例 1
以下程式碼是裝飾器的簡單示例:
def my_function(x): print("The number is=",x) def my_decorator(some_function,num): def wrapper(num): print("Inside wrapper to check odd/even") if num%2 == 0: ret= "Even" else: ret= "Odd!" some_function(num) return ret print ("wrapper function is called") return wrapper no=10 my_function = my_decorator(my_function, no) print ("It is ",my_function(no))
my_function() 只打印接收到的數字。但是,透過將其傳遞給 my_decorator,它的行為被修改了。內部函式接收數字並返回它是奇數還是偶數。上述程式碼的輸出為:
wrapper function is called Inside wrapper to check odd/even The number is= 10 It is Even
示例 2
裝飾函式的一種優雅方式是在其定義之前加上 @ 符號和裝飾器的名稱。上面的例子使用這種表示法重寫:
def my_decorator(some_function): def wrapper(num): print("Inside wrapper to check odd/even") if num%2 == 0: ret= "Even" else: ret= "Odd!" some_function(num) return ret print ("wrapper function is called") return wrapper @my_decorator def my_function(x): print("The number is=",x) no=10 print ("It is ",my_function(no))
Python 的標準庫定義了以下內建裝飾器:
@classmethod 裝飾器
classmethod 是一個內建函式。它將方法轉換為類方法。類方法與例項方法不同。在類中定義的例項方法由其物件呼叫。該方法接收由 self 引用的隱式物件。另一方面,類方法隱式地接收類本身作為第一個引數。
語法
為了宣告類方法,使用以下裝飾器表示法:
class Myclass: @classmethod def mymethod(cls): #....
@classmethod 形式是前面描述的函式裝飾器形式。mymethod 接收對類的引用。它可以由類及其物件呼叫。這意味著 Myclass.mymethod 和 Myclass().mymethod 都是有效的呼叫。
@classmethod 裝飾器的示例
讓我們透過以下示例來了解類方法的行為:
class counter: count=0 def __init__(self): print ("init called by ", self) counter.count=counter.count+1 print ("count=",counter.count) @classmethod def showcount(cls): print ("called by ",cls) print ("count=",cls.count) c1=counter() c2=counter() print ("class method called by object") c1.showcount() print ("class method called by class") counter.showcount()
在類定義中,count 是一個類屬性。__init__() 方法是建構函式,顯然是一個例項方法,因為它接收 self 作為物件引用。宣告的每個物件都會呼叫此方法並將 count 加 1。
@classmethod 裝飾器將 showcount() 方法轉換為類方法,即使它由其物件呼叫,它也接收對類的引用作為引數。即使 c1 物件呼叫 showcount,它也會顯示計數器類的引用。
它將顯示以下輸出:
init called by <__main__.counter object at 0x000001D32DB4F0F0> count= 1 init called by <__main__.counter object at 0x000001D32DAC8710> count= 2 class method called by object called by <class '__main__.counter'> count= 2 class method called by class called by <class '__main__.counter'>
@staticmethod 裝飾器
staticmethod也是Python標準庫中的內建函式。它將一個方法轉換為靜態方法。無論靜態方法是由類的例項還是類本身呼叫,它都不會接收任何引用引數。在類中宣告靜態方法使用以下表示法:
語法
class Myclass: @staticmethod def mymethod(): #....
儘管Myclass.mymethod和Myclass().mymethod都是有效的呼叫,但靜態方法都不會接收任何引用。
@staticmethod裝飾器的示例
計數器類被修改如下:
class counter: count=0 def __init__(self): print ("init called by ", self) counter.count=counter.count+1 print ("count=",counter.count) @staticmethod def showcount(): print ("count=",counter.count) c1=counter() c2=counter() print ("class method called by object") c1.showcount() print ("class method called by class") counter.showcount()
和以前一樣,類屬性count在__init__()方法中每個物件的宣告時都會遞增。但是,由於mymethod()是一個靜態方法,它既不接收self引數也不接收cls引數。因此,類屬性count的值需要顯式引用counter才能顯示。
以上程式碼的輸出如下:
init called by <__main__.counter object at 0x000002512EDCF0B8> count= 1 init called by <__main__.counter object at 0x000002512ED48668> count= 2 class method called by object count= 2 class method called by class count= 2
@property裝飾器
Python的property()內建函式是訪問類例項變數的介面。@property裝飾器將例項方法轉換為具有相同名稱的只讀屬性的“getter”,並將屬性的文件字串設定為“獲取例項變數的當前值”。
可以使用以下三個裝飾器來定義屬性:
@property − 將方法宣告為屬性。
@
.setter: − 指定為屬性設定值的setter方法。@
.deleter − 指定作為刪除屬性的刪除方法。
property()函式返回的屬性物件具有getter、setter和deleter方法。
property(fget=None, fset=None, fdel=None, doc=None)
fget引數是getter方法,fset是setter方法。它可以選擇具有fdel作為刪除物件的方法,doc是文件字串。
語法
property()物件的setter和getter也可以使用以下語法賦值:
speed = property() speed=speed.getter(speed, get_speed) speed=speed.setter(speed, set_speed)
其中get_speed()和set_speeds()是檢索和設定Car類中例項變數speed值的例項方法。
以上語句可以用@property裝飾器實現。使用該裝飾器,car類被改寫為:
@property裝飾器的示例
class car: def __init__(self, speed=40): self._speed=speed return @property def speed(self): return self._speed @speed.setter def speed(self, speed): if speed<0 or speed>100: print ("speed limit 0 to 100") return self._speed=speed return c1=car() print (c1.speed) #calls getter c1.speed=60 #calls setter
屬性裝飾器是一種非常方便且推薦的處理例項屬性的方法。