How to use Sphinx's autodoc to document a class's __init__(self) method?
默认情况下,sphinx不会为uuu init_uuuuu(self)生成文档。我尝试了以下方法:
1 2 | .. automodule:: mymodule :members: |
和
1 2 | ..autoclass:: MyClass :members: |
号
在conf.py中,设置以下内容只会将uuu init_uuuu(self)docstring附加到类docstring(sphinx autodoc文档似乎同意这是预期的行为,但没有提到我要解决的问题):
1 | autoclass_content = 'both' |
以下是三个备选方案:
为了确保
1 2 3 4 5 6 7 | 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) |
这明确定义了不跳过的
在斯芬克斯1.1中增加了
因为sphinx 1.2,这个选项采用的参数比以前更有用。
使用
1 2 3 4 | .. autoclass:: MyClass :members: .. automethod:: __init__ |
号
必须为每个类添加此项(不能与
你很亲密。您可以在
1 | autoclass_content = 'both' |
在过去的几年里,我为各种无关的python项目编写了几种不同的
最近,我采用了最好的实现,并将其作为我的一个Python项目的一部分(以下是文档)。实现主要归结为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | def enable_special_methods(app): """ Enable documenting"special methods" using the autodoc_ extension. :param app: The Sphinx application object. This function connects the :func:`special_methods_callback()` function to ``autodoc-skip-member`` events. .. _autodoc: http://www.sphinx-doc.org/en/stable/ext/autodoc.html """ app.connect('autodoc-skip-member', special_methods_callback) def special_methods_callback(app, what, name, obj, skip, options): """ Enable documenting"special methods" using the autodoc_ extension. Refer to :func:`enable_special_methods()` to enable the use of this function (you probably don't want to call :func:`special_methods_callback()` directly). This function implements a callback for ``autodoc-skip-member`` events to include documented"special methods" (method names with two leading and two trailing underscores) in your documentation. The result is similar to the use of the ``special-members`` flag with one big difference: Special methods are included but other types of members are ignored. This means that attributes like ``__weakref__`` will always be ignored (this was my main annoyance with the ``special-members`` flag). The parameters expected by this function are those defined for Sphinx event callback functions (i.e. I'm not going to document them here :-). """ if getattr(obj, '__doc__', None) and isinstance(obj, (types.FunctionType, types.MethodType)): return False else: return skip |
。
是的,有比逻辑更多的文档:—)。与使用