如何為 Python 函式編寫文件?


文件是編寫程式碼的重要方面,尤其是在涉及函式時。它幫助其他人理解函式的作用、如何使用它以及它接收哪些引數。Python 有一個內建的文件工具,稱為文件字串。文件字串是在函式中作為第一個語句出現的字串,並提供有關該函式的文件。

有關函式或文件的資訊放在函式中的文件字串中。以下是編寫文件字串時應遵循的準則。

第一行應始終是對物件目的的簡短、簡潔的總結。為簡潔起見,它不應明確說明物件的名稱或型別。此行應以大寫字母開頭,以句號結尾。

如果文件字串中還有更多行,則第二行應為空白,在視覺上將摘要與其餘描述分開。

Sphinx

Sphinx 是最流行的 Python 文件工具。它將 reStructuredText 標記語言轉換為一系列輸出格式,包括 HTML、LaTeX(用於可列印的 PDF 版本)、手冊頁和純文字。

執行時,Sphinx 將匯入您的程式碼,並使用 Python 的內省功能提取所有函式、方法和類的簽名。它還將提取伴隨的文件字串,並將所有內容編譯成專案結構良好且易於閱讀的文件。

示例:帶有文件字串的簡單函式

在此示例中,我們定義了一個名為 greet 的函式,它接收一個名為 name 的引數。函式中的第一個語句是文件字串,描述了函式的作用。文件字串用三重引號括起來。

要訪問函式的文件字串,可以使用內建的 help() 函式。

help() 函式顯示函式的文件字串。

def greet(name):
    """
    This function greets the person passed in as a parameter.
    """
    print("Hello, " + name + ". How are you doing?")

# call the function
greet("John")
help(greet)

輸出

Hello, John. How are you doing?
Help on function greet in module __main__:
greet(name)
This function greets the person passed in as a parameter.

示例:帶有詳細文件字串的函式

在此示例中,我們定義了一個名為 calculate_sum 的函式,它接收一個名為 numbers 的引數。函式的文件字串提供了有關函式的更多詳細資訊,包括它接收的引數型別以及它返回的值型別。

同樣,我們可以使用 help() 函式訪問函式的文件字串。

def calculate_sum(numbers):
    """
    This function calculates the sum of a list of numbers.
    
    Parameters:
    numbers (list): A list of numbers to be summed.
    
    Returns:
    int: The sum of the list of numbers.
    """
    total = 0
    for num in numbers:
        total += num
    return total

# call the function
print(calculate_sum([1, 2, 3, 4, 5]))
help(calculate_sum)

輸出

15
Help on function calculate_sum in module __main__:
calculate_sum(numbers)
This function calculates the sum of a list of numbers.
Parameters:
numbers (list): A list of numbers to be summed.
Returns:
int: The sum of the list of numbers.

使用文件字串是為函式提供文件的好方法。它使其他人更容易理解您的程式碼並正確使用您的函式。

記錄您的程式碼是一種重要的實踐,可以為您和可能處理您程式碼的其他開發人員節省時間和精力。正確的文件可以幫助您稍後理解自己的程式碼,並使其他人更容易使用您的程式碼。以下是一些關於如何記錄 Python 函式的技巧 -

示例

記錄 Python 函式最簡單的方法是使用文件字串。文件字串是出現在模組、函式、類或方法定義中的第一個語句的字串文字。可以使用物件的 `__doc__` 屬性訪問它。以下是一個帶有文件字串的函式示例

在此示例中,文件字串提供了有關函式的作用、預期引數以及返回值的資訊。您可以透過執行 `help(add_numbers)` 或 `add_numbers.__doc__` 來訪問文件字串。

def add_numbers(a, b):
    """
    Adds two numbers together.
    :param a: The first number.
    :param b: The second number.
    :return: The sum of a and b.
    """
    return a + b
print(add_numbers.__doc__)

輸出

Adds two numbers together.
   :param a: The first number.
   :param b: The second number.
   :return: The sum of a and b.

示例:使用型別註釋

型別註釋也可用於記錄函式引數和返回值的預期型別。型別註釋是可選的,不影響函式的行為,但可以提高程式碼可讀性並幫助防止錯誤。以下是一個示例

在此示例中,型別註釋表明這兩個引數都應該是整數,並且函式應該返回一個整數。您可以透過執行 `add_numbers.__annotations__` 來訪問型別註釋。

def add_numbers(a:int, b:int) -> int:
    """
    Adds two numbers together.
    :param a: The first number.
    :param b: The second number.
    :return: The sum of a and b.
    """
    return a + b
print(add_numbers.__annotations__)

輸出

{'a': , 'b': , 'return': }

示例:使用文件生成器

雖然文件字串和型別註釋很有用,但編寫和維護它們可能很耗時。文件生成器可以根據這些註釋自動為您的程式碼生成文件。Python 中流行的文件生成器包括 Sphinx 和 pydoc。

Sphinx 是一個流行的文件生成器,用於 Python 和其他程式語言。它可以生成各種格式的文件,例如 HTML、PDF 和 EPUB。Sphinx 使用一種名為 reStructuredText 的標記語言,它類似於 Markdown。

Pydoc 是一個內建的文件生成器,隨 Python 一起提供。它根據文件字串生成文件,可以從命令列執行或用作模組。

以下是用 Sphinx 文件生成器從 `add_numbers` 函式的文件字串生成的示例

def add_numbers(a:int, b:int) -> int:
    """
    Adds two numbers together.
    :param a: The first number.
    :param b: The second number.
    :return: The sum of a and b.
    """
    return a + b

在 Python 模組中定義了上述函式後,您可以使用 Sphinx 為其生成文件,方法是在 .rst 檔案中新增以下 reStructuredText 標記。:members: 選項告訴 Sphinx 為模組中的所有函式和類生成文件。

.. autofunction:: add_numbers
    :members:

將上述標記新增到 .rst 檔案後,您可以使用 sphinx-build 命令生成文件。

sphinx-build -b html source_dir build_dir 

這將為您的 Python 模組生成 HTML 文件,包括 add_numbers 函式。生成的文件將包含函式簽名、文件字串以及您在標記中包含的任何其他相關資訊。

輸出

add_numbers(a, b)
    Adds two numbers together.

    :param a: The first number.
    :param b: The second number.
    :type a: int
    :type b: int
    :return: The sum of a and b.
    :rtype: int

示例:Sphinx 文件生成器

Sphinx 是一個通常用於記錄 Python 專案的文件生成器。它允許您使用 reStructuredText 標記以純文字編寫文件,並從原始碼生成 HTML、PDF 等格式。以下是如何使用 Sphinx 記錄 Python 函式的示例。

首先,您需要安裝 Sphinx。

!pip install sphinx

然後,為您的 Sphinx 文件建立一個新目錄,並使用以下命令對其進行初始化。

sphinx-quickstart

按照提示配置您的 Sphinx 專案。當提示您提供文件根目錄的路徑時,輸入包含 Python 程式碼的目錄的路徑。

專案設定完成後,您可以使用 reStructuredText 標記編寫 Python 函式的文件。

以下是一個示例 -

def greet(name: str) -> str:
    """
    Return a greeting for the given name.
    
    :param name: The name to greet.
    :return: A string greeting.
    """
    return f"Hello, {name}!"

在 `greet` 函式的文件字串中,我們提供了有關函式的作用及其引數的描述。我們使用 reStructuredText 標記來格式化文件字串。

編寫完文件後,您可以使用以下命令生成 HTML 格式的文件。

make html

生成的文件將位於 `_build/html` 目錄中。

示例:Pydoc 文件生成器

Pydoc 是一個內建的 Python 工具,用於從 Python 模組生成文件。它從程式碼中的文件字串生成 HTML 文件。以下是如何使用 Pydoc 的示例。

首先,我們將編寫一個 Python 模組,其中包含我們要記錄的函式。

# mymodule.py

def greet(name):
    """
    Return a greeting for the given name.
    
    :param name: The name to greet.
    :return: A string greeting.
    """
    return f"Hello, {name}!"

接下來,我們可以使用 Pydoc 為我們的模組生成文件。要生成 HTML 文件,請在終端中執行以下命令 -

python -m pydoc -w mymodule

這將在您的當前目錄中生成一個名為 `mymodule.html` 的檔案。您可以在 Web 瀏覽器中開啟 HTML 檔案以檢視文件。

Pydoc 還可以生成其他格式的文件,例如純文字或手冊頁。要生成純文字文件,請執行以下命令。

python -m pydoc mymodule

這會將文件列印到終端。

更新於: 2023年5月19日

368 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.