Sphinx 是否应该能够在 class 中记录实例属性?

Should Sphinx be able to document instance attributes in a class?

我发现了相互矛盾且经常过时的信息,因此希望有人能解决这个问题。

我想使用 Sphinx 记录类似的内容:

class MyClass:
    """
    MyClass, which is documented with a docstring at the class level
    """
    classVar = None
    """A class var with an initial value and a 1-line doc"""

    def __init__(self):
        """
        __init__'s docs
        """
        instanceVar1 = 10
        """An instance var with an initial val and 1-line doc"""

        #: An instance var with an initial val and a doc-comment
        instanceVar2 = 10

在我的文档中,我希望看到 instanceVar1 及其文档字符串(最好是默认值,但我对描述很满意)。但是如果我 运行 的第一个文件是:

.. automodule:: mymodule.mycode
   :members:

我只看到 class 属性,没有看到实例属性:

谷歌搜索给了我关于什么should/shouldn不起作用的相互矛盾的信息。一些较旧的堆栈溢出链引用了实例属性的自动文档化问题(例如 here) but they also refer to it working if you've added docstrings like I've done above. Sphinx docs cite that all attributes can be autodocumented

任何人都可以评论我正在尝试做的事情 work/it 现在对他们是否有效 you/suggestions 我可能搞砸了什么?谢谢。

是的,你所做的应该有效,而且最终对我有效。

为了演示,我使用了您引用的 Sphinx 文档中的示例:

class Foo:
    """Docstring for class Foo."""

    #: Doc comment for class attribute Foo.bar.
    #: It can have multiple lines.
    bar = 1

    flox = 1.5   #: Doc comment for Foo.flox. One line only.

    baz = 2
    """Docstring for class attribute Foo.baz."""

    def __init__(self):
        #: Doc comment for instance attribute qux.
        self.qux = 3

        self.spam = 4
        """Docstring for instance attribute spam."""

我将其保存为 module.py 并创建了以下 index.rst:

.. automodule:: module

连同这个 Sphinx 配置文件,conf.py:

import sys
sys.path.insert(0, '.')
extensions = ['sphinx.ext.autodoc']
autodoc_default_options = {
    'members':         True,
    'member-order':    'bysource',
    'special-members': '__init__',
}

将所有三个文件存储在同一个文件夹中,我通过 sphinx-build . ./html 运行 Sphinx (2.1.1)(在 Python 3.7.3 和 Windows 10 ) 将其呈现为 HTML:

至于你"might have messed up"…嗯,说的很充分,我相信你会同意的。 ;-) 我花了很长时间才意识到这一点,起初,我尝试了与上面相同的方法,但是使用了您提供的代码示例:您的两个所谓的实例属性,instanceVar1instanceVar2,缺少前面的 self 标识符。哎呀。这就是它不起作用的原因。