Python 文档字符串

Python docstrings 是紧跟在函数、方法、类或模块定义之后的字符串字面量。我们来看一个例子。

示例 1:Docstrings

def square(n):
    '''Take a number n and return the square of n.'''
    return n**2

这里,字符串字面量

'''Take a number n and return the square of n.'''

三引号内的内容是函数 square()docstring,因为它紧跟在其定义之后。

注意:我们也可以使用三个 """ 引号来创建 docstrings。


Python 注释 vs Docstrings

Python 注释

注释 是有助于程序员更好地理解程序意图和功能的描述。Python 解释器会完全忽略它们。

在 Python 中,我们使用井号 # 来写单行注释。例如,

# Program to print "Hello World"
print("Hello World") 

Python 注释(使用字符串)

如果我们不将字符串赋值给任何变量,它们就充当注释。例如,

"I am a single-line comment"

'''
I am a
multi-line comment!
'''

print("Hello World")

注意:我们使用三引号来表示多行字符串。

Python docstrings

如上所述,Python docstrings 是紧跟在函数、方法、类或模块定义之后使用的字符串(如示例 1 中所示)。它们用于记录我们的代码。

我们可以使用 __doc__ 属性来访问这些 docstrings。


Python __doc__ 属性

当字符串字面量出现在函数、模块、类或方法的定义之后时,它们将作为其 __doc__ 属性与该对象关联。之后我们可以使用此属性来检索此 docstring。

示例 2:打印 docstring

def square(n):
    '''Take a number n and return the square of n.'''
    return n**2

print(square.__doc__)

输出

Take a number n and return the square of n.

在这里,我们可以使用 __doc__ 属性来访问我们 square() 函数的文档。


现在,我们来看看内置函数 print() 的 docstrings。

示例 3:内置 print() 函数的 Docstrings

print(print.__doc__)

输出

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

在这里,我们可以看到 print() 函数的文档作为该函数的 __doc__ 属性存在。


Python 中的单行 docstrings

单行 docstrings 是适合一行的文档。

编写单行 docstrings 的标准约定

  • 尽管它们是单行的,但我们仍然在这些 docstrings 周围使用三引号,因为它们可以轻松地在以后进行扩展。
  • 结束引号与开始引号在同一行。
  • docstring 前后没有空行。
  • 它们不应冗长,而应遵循“执行此操作,返回该内容”的结构,并以句点结尾。

让我们举个例子。

示例 4:为函数编写单行 docstrings

def multiplier(a, b):
    """Take two numbers and return their product."""
    return a*b

Python 中的多行 Docstrings

多行 docstrings 包含一个摘要行,就像单行 docstring 一样,后面是一个空行,然后是一个更详细的描述。

PEP 257 文档提供了为各种对象编写多行 docstrings 的标准约定。

下面列出了一些


1. Python 模块的 Docstrings

  • Python 模块的 docstrings 应列出导入模块时导入的所有可用类、函数、对象和异常。
  • 它们还应为每个项目提供一个单行摘要。

它们写在 Python 文件的开头。

我们来看一下 Python 中名为 pickle 的内置模块的 docstrings。

示例 4:Python 模块的 Docstrings

import pickle
print(pickle.__doc__)

输出

Create portable serialized representations of Python objects.

See module copyreg for a mechanism for registering custom picklers.
See module pickletools source for extensive comments.

Classes:

    Pickler
    Unpickler

Functions:

    dump(object, file)
    dumps(object) -> string
    load(file) -> object
    loads(string) -> object

Misc variables:

    __version__
    format_version
    compatible_formats

在这里,我们可以看到写在 pickle.py 模块文件开头的 docstring 可以作为其 docstring 访问。


2. Python 函数的 Docstrings

  • 函数或方法的 docstring 应总结其行为并记录其参数和返回值。
  • 它还应列出所有可能引发的异常和其他可选参数。

示例 5:Python 函数的 Docstrings

def add_binary(a, b):
    '''
    Return the sum of two decimal numbers in binary digits.

            Parameters:
                    a (int): A decimal integer
                    b (int): Another decimal integer

            Returns:
                    binary_sum (str): Binary string of the sum of a and b
    '''
    binary_sum = bin(a+b)[2:]
    return binary_sum


print(add_binary.__doc__)

输出

Returns the sum of two decimal numbers in binary digits.

	Parameters:
		a (int): A decimal integer
		b (int): Another decimal integer

	Returns:
		binary_sum (str): Binary string of the sum of a and b

如您所见,我们包含了对函数功能、它接受的参数以及它返回的值的简短描述。字符串字面量嵌入到函数 add_binary 中,作为其 __doc__ 属性。


3. Python 类的 Docstrings

  • 类的 docstrings 应总结其行为并列出公共方法和实例变量。
  • 子类、构造函数和方法都应具有自己的 docstrings。

示例 6:Python 类的 Docstrings

假设我们有一个 Person.py 文件,其中包含以下代码

class Person:
    """
    A class to represent a person.

    ...

    Attributes
    ----------
    name : str
        first name of the person
    surname : str
        family name of the person
    age : int
        age of the person

    Methods
    -------
    info(additional=""):
        Prints the person's name and age.
    """

    def __init__(self, name, surname, age):
        """
        Constructs all the necessary attributes for the person object.

        Parameters
        ----------
            name : str
                first name of the person
            surname : str
                family name of the person
            age : int
                age of the person
        """

        self.name = name
        self.surname = surname
        self.age = age

    def info(self, additional=""):
        """
        Prints the person's name and age.

        If the argument 'additional' is passed, then it is appended after the main info.

        Parameters
        ----------
        additional : str, optional
            More info to be displayed (default is None)

        Returns
        -------
        None
        """

        print(f'My name is {self.name} {self.surname}. I am {self.age} years old.' + additional)

在这里,我们可以使用以下代码来仅访问 Person 类的 docstrings

print(Person.__doc__)

输出

    A class to represent a person.

    ...

    Attributes
    ----------
    name : str
        first name of the person
    surname : str
        family name of the person
    age : int
        age of the person

    Methods
    -------
    info(additional=""):
        Prints the person's name and age

使用 help() 函数获取 Docstrings

我们还可以使用 help() 函数来读取与各种对象关联的 docstrings。

示例 7:使用 help() 函数读取 Docstrings

我们可以像这样在示例 6 中的 Person 类上使用 help() 函数:

help(Person)

输出

Help on class Person in module __main__:

class Person(builtins.object)
 |  Person(name, surname, age)
 |  
 |  A class to represent a person.
 |  
 |  ...
 |  
 |  Attributes
 |  ----------
 |  name : str
 |      first name of the person
 |  surname : str
 |      family name of the person
 |  age : int
 |      age of the person
 |  
 |  Methods
 |  -------
 |  info(additional=""):
 |      Prints the person's name and age.
 |  
 |  Methods defined here:
 |  
 |  __init__(self, name, surname, age)
 |      Constructs all the necessary attributes for the person object.
 |      
 |      Parameters
 |      ----------
 |          name : str
 |              first name of the person
 |          surname : str
 |              family name of the person
 |          age : int
 |              age of the person
 |  
 |  info(self, additional='')
 |      Prints the person's name and age.
 |      
 |      If the argument 'additional' is passed, then it is appended after the main info.
 |      
 |      Parameters
 |      ----------
 |      additional : str, optional
 |          More info to be displayed (default is None)
 |      
 |      Returns
 |      -------
 |      None
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

在这里,我们可以看到 help() 函数检索了 Person 类的 docstrings 以及与该类相关联的方法。


 

4. Python 脚本的 Docstrings

  • Python 脚本的 docstrings 应记录脚本的功能和命令行语法,作为可用的消息。
  • 它应该作为所有函数和参数的快速参考。

5. Python 包的 Docstrings

Python 包的 docstrings 写在包的 __init__.py 文件中。

  • 它应包含包导出的所有可用模块和子包。

Docstring 格式

我们可以用多种格式编写 docstring,例如 reStructured text (reST) 格式、Google 格式或 NumPy 文档格式。要了解更多信息,请访问 流行的 Docstring 格式

我们还可以使用 Sphinx 等工具从 docstrings 生成文档。要了解更多信息,请访问 官方 Sphinx 文档

视频:Python docstrings

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战