Python - 文件字串



Python 中的文件字串

在 Python 中,文件字串是用於記錄模組、類、函式和方法的一種方式。它們寫在三個引號(""" """)內,可以跨多行。

文件字串是將文件與 Python 程式碼關聯的便捷方式。可以透過各自 Python 物件的__doc__屬性訪問它們。以下是編寫文件字串的不同方法:

單行文件字串

單行文件字串用於簡短簡單的文件。它們提供了對函式或方法作用的簡潔描述。單行文件字串應適合在一行三引號內,並以句點結尾。

示例

在下面的示例中,我們使用單行文件字串來編寫文字:

def add(a, b):
   """Return the sum of two numbers."""
   return a + b

result = add(5, 3)
print("Sum:", result)

多行文件字串

多行文件字串用於更詳細的文件。它們提供更全面的描述,包括引數、返回值和其他相關細節。多行文件字串以三個引號開頭和結尾,包含摘要行,後跟空行和更詳細的描述。

示例

以下示例使用多行文件字串來解釋程式碼:

def multiply(a, b):
   """
   Multiply two numbers and return the result.

   Parameters:
   a (int or float): The first number.
   b (int or float): The second number.

   Returns:
   int or float: The result of multiplying a and b.
   """
   return a * b
result = multiply(5, 3)
print("Product:", result)

模組的文件字串

為模組編寫文件字串時,請將文件字串放在模組頂部,緊跟在任何 import 語句之後。模組文件字串提供了模組功能的概述,並列出了其主要元件,例如模組提供的函式、類和異常列表。

示例

在此示例中,我們演示了在 Python 中使用模組文件字串:

import os

"""
This module provides Utility functions for file handling operations.

Functions:
- 'read_file(filepath)': Reads and returns the contents of the file.
- 'write_file(filepath, content)': Writes content to the specified file.

Classes:
- 'FileNotFoundError': Raised when a file is not found.

Example usage:

   >>> import file_utils
   >>> content = file_utils.read_file("example.txt")
   >>> print(content)
   'Hello, world!'
   >>> file_utils.write_file("output.txt", "This is a test.")
"""
print("This is os module")

類的文件字串

類可以包含文件字串來描述其目的和用法。類中的每個方法也可以有自己的文件字串。類文件字串應提供對類及其方法的概述。

示例

在下面的示例中,我們展示了在 Python 中使用類文件字串:

class Calculator:
   """
   A simple calculator class to perform basic arithmetic operations.

   Methods:
   - add(a, b): Return the sum of two numbers.
   - multiply(a, b): Return the product of two numbers.
   """

   def add(self, a, b):
      """Return the sum of two numbers."""
      return a + b

   def multiply(self, a, b):
      """
      Multiply two numbers and return the result.

      Parameters:
      a (int or float): The first number.
      b (int or float): The second number.

      Returns:
      int or float: The result of multiplying a and b.
      """
      return a * b
	  
cal = Calculator()
print(cal.add(87, 98))
print(cal.multiply(87, 98))

訪問文件字串

Python 中的文件字串是使用它們所記錄物件的__doc__屬性訪問的。此屬性包含與物件關聯的文件字串,提供了一種訪問和顯示有關函式、類、模組或方法的目的和用法的的資訊的方法。

示例

在下面的示例中,我們定義了兩個函式“add”和“multiply”,每個函式都有一個描述其引數和返回值的文件字串。然後,我們使用“__doc__”屬性來訪問和列印這些文件字串:

# Define a function with a docstring
def add(a, b):
    """
    Adds two numbers together.

    Parameters:
    a (int): The first number.
    b (int): The second number.

    Returns:
    int: The sum of a and b.
    """
    return a + b
result = add(5, 3)
print("Sum:", result)

# Define another function with a docstring
def multiply(x, y):
    """
    Multiplies two numbers together.

    Parameters:
    x (int): The first number.
    y (int): The second number.

    Returns:
    int: The product of x and y.
    """
    return x * y
result = multiply(4, 7)
print("Product:", result)

# Accessing the docstrings
print(add.__doc__)
print(multiply.__doc__)

編寫文件字串的最佳實踐

以下是 Python 中編寫文件字串的最佳實踐:

  • 清晰簡潔 - 確保文件字串清楚地解釋了程式碼的目的和用法,避免不必要的細節。

  • 使用正確的語法和拼寫 - 確保文件字串書寫良好,語法和拼寫正確。

  • 遵循約定 - 使用標準的文件字串格式約定,例如 Google 風格、NumPy 風格或 Sphinx 風格。

  • 包含示例 - 在適用情況下提供示例來說明如何使用已記錄的程式碼。

Google 風格文件字串

Google 風格文件字串提供了一種使用縮排和標題來記錄 Python 程式碼的結構化方法。它們旨在易於閱讀和資訊豐富,並遵循特定的格式。

示例

以下是具有 Google 風格文件字串的函式示例:

def divide(dividend, divisor):
   """
   Divide two numbers and return the result.

   Args:
      dividend (float): The number to be divided.
      divisor (float): The number to divide by.

   Returns:
      float: The result of the division.

   Raises:
      ValueError: If `divisor` is zero.
   """
   if divisor == 0:
      raise ValueError("Cannot divide by zero")
   return dividend / divisor

result = divide(4, 7)
print("Division:", result)

NumPy/SciPy 風格文件字串

NumPy/SciPy 風格的文件字串在科學計算中很常見。它們包含引數、返回值和示例等部分。

示例

下面是一個帶有 NumPy/SciPy 風格文件字串的函式示例:

def fibonacci(n):
   """
   Compute the nth Fibonacci number.

   Parameters
   ----------
   n : int
      The index of the Fibonacci number to compute.

   Returns
   -------
   int
      The nth Fibonacci number.

   Examples
   --------
   >>> fibonacci(0)
   0
   >>> fibonacci(5)
   5
   >>> fibonacci(10)
   55
   """
   if n == 0:
      return 0
   elif n == 1:
      return 1
   else:
      return fibonacci(n-1) + fibonacci(n-2)
	  
result = fibonacci(4)
print("Result:", result)	  

Sphinx 風格文件字串

Sphinx 風格的文件字串與 Sphinx 文件生成器相容,並使用reStructuredText 格式。

reStructuredText (reST) 是一種輕量級的標記語言,用於建立結構化文字文件。Sphinx 文件生成器以 “reStructuredText” 檔案作為輸入,並生成各種格式的高質量文件,包括 HTML、PDF、ePub 等。

示例

下面是一個帶有 Sphinx 風格文件字串的函式示例:

def divide(dividend, divisor):
   """
   Divide two numbers and return the result.

   Args:
      dividend (float): The number to be divided.
      divisor (float): The number to divide by.

   Returns:
      float: The result of the division.

   Raises:
      ValueError: If `divisor` is zero.
   """
   if divisor == 0:
      raise ValueError("Cannot divide by zero")
   return dividend / divisor
   
result = divide(76, 37)
print("Result:", result)

文件字串與註釋

以下是 Python 文件字串和註釋之間差異的重點,分別關注它們的用途、格式、用法和可訪問性:

文件字串 註釋
用於記錄 Python 物件,例如函式、類、方法、模組或包。 用於為人類讀者註釋程式碼,提供上下文或暫時停用程式碼。
用三個引號 (""" """ 或 ''' ''') 編寫,並放置在物件定義的緊後。 以 # 符號開頭,並放置在與註釋程式碼相同的行上。
儲存為物件的屬性,並且可以透過程式設計方式訪問。 Python 直譯器在執行期間會忽略它,純粹是為了人類理解。
使用物件的 __doc__ 屬性訪問。 無法透過程式設計方式訪問;僅存在於原始碼中。
廣告