MEMOO
MEMOO
Published on 2025-04-18 / 2 Visits
0
0

Python文档字符串

摘要:在本节中,你将学习如何使用文档字符串为函数添加文档说明。

help() 函数简介

Python 提供了一个名为 help() 的内置函数,它能让你查看一个函数的文档说明。

以下示例展示了 print() 函数的文档说明:

help(print)

输出:

Help on built-in function print in module builtins:

print(*args, sep=' ', end='\n', file=None, flush=False)
    Prints the values to a stream, or to sys.stdout by default.

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

请注意,你可以使用 help() 函数来显示模块、类、函数和关键字的文档说明。本节仅专注于函数的文档说明。

使用文档字符串来为函数编写文档

为了给你的函数编写文档,你可以使用文档字符串。PEP 257提供了文档字符串的规范。

当函数体中的第一行是一个字符串时,Python 会将其解释为一个文档字符串。例如:

def add(a, b):

    "Return the sum of two arguments"

    return a + b

并且你可以使用 help() 函数来查找 add() 函数的文档说明:

def add(a, b):

    "Return the sum of two arguments"

    return a + b

help(add)

输出:

add(a, b)

    Return the sum of two arguments

通常情况下,你会使用多行文档字符串:

def add(a, b):

    """ Add two arguments

    Arguments:

        a: an integer

        b: an integer

    Returns:

        The sum of the two arguments

    """

    return a + b

help(add)

输出:

add(a, b)

    Add the two arguments

    Arguments:

            a: an integer

            b: an integer

        Returns:

            The sum of the two arguments        

Python 将文档字符串存储在函数的 __doc__ 属性中。

以下示例展示了如何访问 add() 函数的 __doc__ 属性:

def add(a, b):

    """ Add two arguments

    Arguments:

        a: an integer

        b: an integer

    Returns:

        The sum of the two arguments

    """

    return a + b

print(add.__doc__)

总结

  • 使用 help() 函数来获取一个函数的文档说明。

  • 将一个字符串(可以是单行字符串或多行字符串)放在函数的第一行,以便为该函数添加文档说明。


Comment