【问题标题】:Should Sphinx be able to document instance attributes in a class?Sphinx 是否应该能够记录类中的实例属性?
【发布时间】:2019-06-20 21:02:29
【问题描述】:

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

我想用 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:

我只看到类属性,而不是实例属性:

谷歌搜索给了我关于什么应该/不应该起作用的相互矛盾的信息。一些较旧的堆栈溢出链引用了实例属性的自动文档问题(例如here),但如果您像我上面所做的那样添加了文档字符串,它们也会引用它。 Sphinx 文档引用了all attributes can be autodocumented

任何人都可以评论我正在尝试做的事情是否应该工作/它现在对他们有用吗/关于我可能搞砸的建议?谢谢。

【问题讨论】:

  • 也许我遗漏了一些东西,但这不是here 描述的用于 bar、baz、quz 和 spam 的格式吗?
  • Automodule 只会使用文档字符串,你真的使用自动属性吗? FWIW 我通常使用sphinx-doc.org/en/master/usage/extensions/napoleon.html 以获得更易于阅读的源代码。

标签: python python-sphinx autodoc


【解决方案1】:

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

为了演示,我使用了您引用的 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(在 Python 3.7.3 和 Windows 10 上)运行 Sphinx (2.1.1) 以将其呈现为 HTML:

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

【讨论】:

  • 天哪,真尴尬。难怪我昨天拔头发了。我从一个真实的包(它实际上使用了 self...)开始,其中实例变量的文档不正确,所以我将其简化为上面的示例以进行故障排除。结果我不小心添加了一个错误,它复制了我试图排除故障的同一件事!还没有真正修复我的真实模块,但这给了我一个可行的例子!
猜你喜欢
  • 2022-06-15
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多