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

对于模糊之处,我深表歉意,但示例的一部分有些敏感
您有多种选项来记录类级别变量。
将以 开头的注释放在#:变量之前或同一行上。(仅使用自动文档。)
也许是最简单的选择。如果需要,您可以使用选项自定义值:annotation:。如果您想键入提示值,请使用#: type:.
在变量后面放置文档字符串。
如果变量需要大量文档,则很有用。
在类文档字符串中记录变量。(使用 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)
结果:

| 归档时间: |
|
| 查看次数: |
3789 次 |
| 最近记录: |