如何使用Sphinx的autodoc来文档类的__init__(self)方法?
Sphinx 默认情况下不会为 __init__(self) 生成文档。我尝试了以下方法:
.. automodule:: mymodule
:members:
还有
..autoclass:: MyClass
:members:
在 conf.py 文件中,设置以下内容只会将 __init__(self) 的文档字符串附加到类的文档字符串中(Sphinx 的自动文档说明似乎也同意这是预期的行为,但没有提到我想解决的问题):
autoclass_content = 'both'
6 个回答
15
虽然这是一篇较旧的帖子,但对于现在还在查找这个问题的人来说,1.8版本中也有另一个解决方案。根据文档,你可以在你的conf.py
文件中添加autodoc_default_options
里的special-members
键。
举个例子:
autodoc_default_options = {
'members': True,
'member-order': 'bysource',
'special-members': '__init__',
'undoc-members': True,
'exclude-members': '__weakref__'
}
95
你差不多说对了。你可以在你的 conf.py
文件中使用 autoclass_content
这个选项:
autoclass_content = 'both'
129
这里有三种替代方案:
为了确保
__init__()
总是被记录,你可以在 conf.py 文件中使用autodoc-skip-member
。像这样:def skip(app, what, name, obj, would_skip, options): if name == "__init__": return False return would_skip def setup(app): app.connect("autodoc-skip-member", skip)
这明确表示
__init__
不会被跳过(默认情况下是会被跳过的)。这个设置只需要定义一次,不需要在每个类的 .rst 源文件中额外添加标记。special-members
选项是在 Sphinx 1.1 中 新增的。它可以让那些名字带有__special__
的“特殊”成员被自动记录。自 Sphinx 1.2 以来,这个选项可以接收参数,使它比之前更有用。
使用
automethod
:.. autoclass:: MyClass :members: .. automethod:: __init__
这个需要为每个类单独添加(不能和
automodule
一起使用,正如这个答案的第一版评论中提到的)。