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

2024-07-04 10:49:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我想用狮身人面像记录这样的东西:

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文件是:

^{pr2}$

我只看到类属性,没有看到实例属性: Image showing docs

谷歌给我的信息相互矛盾,哪些应该/不应该起作用。一些较旧的堆栈溢出链引用了实例属性(例如here)的自动文档编制问题,但是如果像我上面所做的那样添加了docstring,它们也会指出它是有效的。斯芬克斯的文献引用了all attributes can be autodocumented。在

有人能评论一下我现在所做的是否对他们有用你/我可能搞错了什么的建议?谢谢。在


Tags: andan信息doc属性initvarwith
1条回答
网友
1楼 · 发布于 2024-07-04 10:49:49

是的,你所做的应该管用,而且它最终对我有用。在

为了证明这一点,我使用了你引用的斯芬克斯文献中的例子:

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

^{pr2}$

以及这个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(在Python 3.7.3和Windows 10上)运行Sphinx(2.1.1)将其呈现为HTML: rendered HTML

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

相关问题 更多 >

    热门问题