在 Python 中记录类级变量

PCa*_*rgo 3 restructuredtext docstring python-sphinx autodoc sphinx-napoleon

我正在尝试记录一个具有一些类级成员变量的 Python 类,但我无法使用 reST/Sphinx 对其进行适当记录。

代码是这样的:

class OSM:
    """Some blah and examples"""
    url = 'http://overpass-api.de/api/interpreter'  # URL of the Overpass API
    sleep_time = 10  # pause between successive queries when assembling OSM dataset
Run Code Online (Sandbox Code Playgroud)

但我得到了这个输出(请参见绿色圆圈区域,我希望在其中有一些描述这两个变量的文本,如上所述)。

在此输入图像描述

对于模糊之处,我深表歉意,但示例的一部分有些敏感

bad*_*der 5

您有多种选项来记录类级别变量。

  1. 将以 开头的注释放在#:变量之前或同一行上。(仅使用自动文档。)

    也许是最简单的选择。如果需要,您可以使用选项自定义值:annotation:。如果您想键入提示值,请使用#: type:.

  2. 在变量后面放置文档字符串。

    如果变量需要大量文档,则很有用。

    对于模块数据成员和类属性,文档可以放入具有特殊格式的注释中(使用 #: 来开始注释而不只是 #),也可以放入定义后的文档字符串中。注释需要在定义之前单独占一行,或者在同一行的赋值之后。后一种形式仅限于一行。

  3. 在类文档字符串中记录变量。(使用 sphinx-napoleon 扩展,如示例所示。)

    这样做的缺点是变量的值将被省略。由于它是类级别变量,如果您没有在变量前添加cls.or前缀,则 IDE 的静态类型检查器可能会报错class_name.。然而这种区别很方便,因为实例变量也可以记录在类文档字符串中。

以下示例显示了所有三个选项。.rst为了说明所需的功能,它具有额外的复杂性autodoc。所有情况下都包含类型提示,但也可以省略。

class OSM:
    """Some blah and examples"""

    #: str: URL of the Overpass API.
    url = 'http://overpass-api.de/api/interpreter'
    #: int: pause between successive queries when assembling OSM dataset.
    sleep_time = 10


class OSM2:
    """Some blah and examples.

    Attributes:
        cls.url (str): URL of the Overpass API.
    """

    url = 'http://overpass-api.de/api/interpreter'

    sleep_time = 10
    """str: Docstring of sleep_time after the variable."""
Run Code Online (Sandbox Code Playgroud)

相应的.rst

OSM module
==========

.. automodule:: OSM_module
    :members:
    :exclude-members: OSM2

    .. autoclass:: OSM2
        :no-undoc-members:
        :exclude-members: sleep_time

        .. autoattribute:: sleep_time
            :annotation: = "If you want to specify a different value from the source code."
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述