在Python中记录类级变量

问题描述

我正在尝试记录具有某些类级成员变量的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

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

enter image description here

我为模糊表示歉意,但示例的一部分有些敏感

解决方法

您可以使用多个选项来记录类级别的变量。

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

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

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

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

    For module data members and class attributes,documentation can either be put into a comment with special formatting (using a #: to start the comment instead of just #),or in a docstring after the definition. Comments need to be either on a line of their own before the definition,or immediately after the assignment on the same line. The latter form is restricted to one line only.

  3. 在类文档字符串中记录变量。 (使用狮身人面像-拿破仑扩展名shown in the example。)

    其缺点是将省略变量的值。由于它是一个类级别的变量,因此如果您不为变量加上前缀cls.class_name.,则IDE的静态类型检查器可能会抱怨。但是,这种区别很方便,因为实例变量也可以记录在docstring类中。

以下示例显示了所有三个选项。 .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."""

对应的.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."

结果:

enter image description here