Python 註解技巧


建立時間: 2022年9月3日 20:13
更新時間: 2022年12月30日 03:10

基本註解

最基本的註解就是單行註解和多行註解

# 這是單行註解

"""
這是
多行註解
"""

文檔字串註解 Docstring

文檔註解用來說明函式,而且有些編輯器,
自動提示選項的函式時會顯示 docstring 的內容

def calculate_addition(augend, addend):
    """計算加法

    Args:
        augend (int): 被加數
        addend (int): 加數

    Returns:
        int: 和
    """

    return augend + addend

註解寫在函式裡面,有些程式語言註解是寫在函式上面
函式註解採用多行註解的方式
第一行是註解說明,如上面的計算加法
Args 是參數,格式是: 參數名稱 (型態): 說明
Returns 是回傳,格式是: 型態: 說明

你還可以調用函式註解內容

print(calculate_addition.__doc__)

typing 變數註解語法

這可以幫助你寫出更堅固的程式
而且可以幫助編輯器自動提示功能,提供語法建議
因為有時候編輯器不知道變數型態,例如函式參數是某個物件
當編輯器不知道型態時,可能會判斷成 Any 任何型態

class Starship:
    captain: str = 'Picard'
    damage: int
    stats: ClassVar[dict[str, int]] = {}

    def __init__(self, damage: int, captain: str = None):
        self.damage = damage
        if captain:
            self.captain = captain  # Else keep the default

    def hit(self):
        Starship.stats['hits'] = Starship.stats.get('hits', 0) + 1

enterprise_d = Starship(3000)
enterprise_d.stats = {} # Flagged as error by a type checker
Starship.stats = {} # This is OK

你看到類似這種 : 型態 ,例如 : int 就是變數註解語法
dict[str, int] 就是 字典[鍵型態, 值型態]
這個內容水很深,有興趣的讀者可以到參考連結 PEP 526 – Syntax for Variable Annotations 查看更多

Union

當變數同時存在多種可能,可以用 Union
語法是:
python 3.10 以下 Union[X, Y]
python 3.10 X | Y

例如最常見的應該是字典的值可能是 str 或 int

from typing import Union

result: dict[str, Union[int, str]] = {
    'count': 0,
    'date': '2022-02-02',
}

Forward references

當變數型別是當前的類別時,需要使用前向參考,前向參考的說明可以參考 Forward references ,意思大概是型態未定義好,先用字串名稱充當一下,之後再解析成正確的型態。

以下 left 型態為 Tree,但在定義 left 型態時,Tree 還沒定義好,所以先用字串的方式定義,告訴程式這之後再解析,之後就是等到 Tree 定義好,解釋有點粗糙,詳細說明請參考上方連結。

Tree.py

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

總結

當你慢慢會使用這些註解技巧之後,程式就會越來越清楚
對於以後的開發人員(也許是你自己)會很有幫助

參考

觀看次數: 2969
annotationscommentpython註解
按讚追蹤 Enjoy 軟體 Facebook 粉絲專頁
每週分享資訊技術

一杯咖啡的力量,勝過千言萬語的感謝。

支持我一杯咖啡,讓我繼續創作優質內容,與您分享更多知識與樂趣!