Python 简明教程
Python - Docstrings
Docstrings in Python
在 Python 中,文档字符串是一种对模块、类、函数和方法进行编制文档的方式。它们位于三引号 (""" """) 内,并且可能跨越多行。
In Python, docstrings are a way of documenting modules, classes, functions, and methods. They are written within triple quotes (""" """) and can span multiple lines.
文档字符串是 Python 代码编写文档的便捷方式。它们可通过 doc 访问它们编制文档的相应 Python 对象的属性。以下是编写文档字符串的不同方式。
Docstrings serve as convenient way of associating documentation with Python code. They are accessible through the doc attribute of the respective Python objects they document. Below are the different ways to write docstrings −
Single-Line Docstrings
单行文档字符串用于简短而简单的文档。它们提供对函数或方法的作用的简洁描述。单行文档字符串应放在三引号内的一行中,并以句点结尾。
Single-line docstrings are used for brief and simple documentation. They provide a concise description of what the function or method does. Single-line docstrings should fit on one line within triple quotes and end with a period.
Multi-Line Docstrings
多行文档字符串用于制作更详细的文档。它们提供更全面的描述,包括参数、返回值和其他相关详细信息。多行文档字符串以三引号开头和结尾,包括一行摘要,后面是空行和更详细的描述。
Multi-line docstrings are used for more detailed documentation. They provide a more comprehensive description, including the parameters, return values, and other relevant details. Multi-line docstrings start and end with triple quotes and include a summary line followed by a blank line and a more detailed description.
Example
以下示例使用多行文档字符串来解释代码。
The following example uses multi-line docstrings as an explanation of the code −
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)
Docstrings for Modules
为模块编写文档字符串时,应把文档字符串放在模块顶部,紧跟在任何 import 语句之后。模块文档字符串提供模块功能的概述,并列出其主要组件,例如模块提供的函数、类和异常的列表。
When writing docstrings for modules, place the docstring at the top of the module, right after any import statements. The module docstring provide an overview of the module’s functionality and list its primary components, such as list of functions, classes, and exceptions provided by the module.
Example
在本例中,我们演示了在 Python 中为模块使用文档字符串。
In this example, we demonstrate the use of docstrings for modules in 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")
Docstrings for Classes
类可以有文档字符串来描述其目的和用法。类中的每个方法也可以有自己的文档字符串。类文档字符串应提供该类的概览及其方法。
Classes can have docstrings to describe their purpose and usage. Each method within the class can also have its own docstring. The class docstring should provide an overview of the class and its methods.
Example
在下面的示例中,我们展示了在 Python 中为类使用文档字符串。
In the example below, we showcase the use of docstrings for classes in 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))
Accessing Docstrings
Python 中的文档字符串可使用 doc 访问它们编制文档的对象的属性。此属性包含与对象关联的文档字符串(文档字符串),从而能够访问和显示有关函数、类、模块或方法的目的和用法的的信息。
Docstrings in Python are accessed using the doc attribute of the object they document. This attribute contains the documentation string (docstring) associated with the object, providing a way to access and display information about the purpose and usage of functions, classes, modules, or methods.
Example
在以下示例中,我们定义了两个函数“add”和“multiply”,每个函数都有一个含参和返回值描述的 docstring。然后,我们使用 “ doc ” 属性以访问并打印这些 docstring −
In the following example, we are defining two functions, "add" and "multiply", each with a docstring describing their parameters and return values. We then use the "doc" attribute to access and print these docstrings −
# 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__)
Best Practices for Writing Docstrings
以下是在 Python 中编写 docstring 的最佳实践 −
Following are the best practices for writing docstrings in Python −
-
Be Clear and Concise − Ensure the docstring clearly explains the purpose and usage of the code, avoiding unnecessary details.
-
Use Proper Grammar and Spelling − Ensure the docstring is well-written with correct grammar and spelling.
-
Follow Conventions − Use the standard conventions for formatting docstrings, such as the Google style, NumPy style, or Sphinx style.
-
Include Examples − Provide examples where applicable to illustrate how to use the documented code.
Google Style Docstring
Google 样式 docstring 使用缩进和标题提供一种结构化的方式来记录 Python 代码。它们设计为可读和信息丰富,遵循特定格式。
Google style docstrings provide a structured way to document Python code using indentation and headings. They are designed to be readable and informative, following a specific format.
Example
以下是具有 Google 样式 docstring 的函数示例 −
Following is an example of a function with a Google style docstring −
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 Style Docstring
NumPy/SciPy 样式 docstring 在科学计算中很常见。它们包括参数、返回值和示例部分。
NumPy/SciPy style docstrings are common in scientific computing. They include sections for parameters, returns, and examples.
Example
以下是具有 NumPy/SciPy 样式 docstring 的函数示例 −
Following is an example of a function with a NumPy/SciPy style docstring −
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 Style Docstring
Sphinx 样式 docstring 与 Sphinx 文档生成器兼容,并使用 reStructuredText 格式。
Sphinx style docstrings are compatible with the Sphinx documentation generator and use reStructuredText formatting.
reStructuredText (reST) 是一种用于创建结构化文本文档的轻量级标记语言。Sphinx 文档生成器将 “reStructuredText” 文件作为输入,并以各种格式生成高质量的文档,包括 HTML、PDF、ePub 等。
The reStructuredText (reST) is a lightweight markup language used for creating structured text documents. The Sphinx documentation generator takes "reStructuredText" files as input and generates high-quality documentation in various formats, including HTML, PDF, ePub, and more.
Example
以下是具有 Sphinx 样式 docstring 的函数示例 −
Following is an example of a function with a Sphinx style docstring −
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)