Python Sphinx应该能够在类中记录实例属性吗?

Python Sphinx应该能够在类中记录实例属性吗?,python,python-sphinx,autodoc,Python,Python Sphinx,Autodoc,我发现了一些相互矛盾且经常过时的信息,希望有人能澄清这一点 我想用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__(se

我发现了一些相互矛盾且经常过时的信息,希望有人能澄清这一点

我想用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及其docstring(理想情况下是默认值,但我只希望看到描述)。但如果我运行的rst文件为:

.. automodule:: mymodule.mycode
   :members:
我只看到类属性,没有看到实例属性:

谷歌搜索给了我关于什么应该/不应该有效的相互矛盾的信息。一些旧的堆栈溢出链引用了实例属性(如)的自动文档编制问题,但如果您像我上面所做的那样添加了docstring,它们也会提到它的工作。斯芬克斯医生引用了这一点

有谁能评论一下我正在尝试做的事情是否对他们有效/现在对他们有效/你/我可能会把事情搞砸的建议?谢谢。

是的,你所做的应该有用,而且——最终——对我有用

为了演示,我使用了您引用的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

。。自动模块::模块
与此Sphinx配置文件一起,
conf.py

import sys
sys.path.insert(0, '.')
extensions = ['sphinx.ext.autodoc']
autodoc_default_options = {
    'members':         True,
    'member-order':    'bysource',
    'special-members': '__init__',
}
所有三个文件都存储在同一个文件夹中,我通过
sphinxbuild运行了Sphinx(2.1.1)/html
(在Python 3.7.3和Windows 10上)将其呈现为html:


至于你“可能把事情搞砸了”…嗯,这已经足够了,我相信你会同意的我花了很长时间才意识到这一点,起初,我尝试了与上面相同的方法,但使用了您提供的代码示例:两个所谓的实例属性,
instanceVar1
instanceVar2
,缺少前面的
self
标识符。哎呀。这就是它不起作用的原因。

也许我遗漏了一些东西,但这不是bar、baz、quz和spam所描述的格式吗?Automodule将只使用DocString,您实际使用autoattribute吗?我通常使用FWIW来获取更易于阅读的源代码。哦,天哪,这太尴尬了。难怪我昨天把头发拔了出来。我从一个实际的包开始(它实际上使用self…),其中实例变量没有正确地对接,所以我将其简化为上面的示例来进行故障排除。原来我无意中添加了一个错误,它复制了我试图解决的问题!实际上还没有修复我真正的模块,但这给了我一个工作示例!