【问题标题】:Documenting class-level variables in Python在 Python 中记录类级变量
【发布时间】:2021-02-24 00:54:53
【问题描述】:

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

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

我为模糊道歉,但部分示例有些敏感

【问题讨论】:

标签: python-sphinx restructuredtext docstring autodoc sphinx-napoleon


【解决方案1】:

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

  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. 在类文档字符串中记录变量。 (使用 sphinx-napoleon 扩展,shown in the example。)

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

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

结果:

【讨论】:

  • 我测试了建议 #1,效果很好。谢谢!!
猜你喜欢
  • 2015-02-03
  • 1970-01-01
  • 2019-04-10
  • 2023-04-04
  • 1970-01-01
  • 2022-08-19
  • 2016-03-05
  • 2011-11-11
相关资源
最近更新 更多