如何使用Sphinx的autodoc来logging类的__init __(self)方法?
Sphinx默认情况下不会为__init __(self)生成文档。 我已经尝试了以下内容:
.. automodule:: mymodule :members: 
和
 ..autoclass:: MyClass :members: 
在conf.py中,设置以下内容只会将__init __(self)docstring附加到类docstring中( Sphinx autodoc文档似乎认同这是预期的行为,但没有提到我正试图解决的问题):
 autoclass_content = 'both' 
	
这里有三个select:
- 
要确保
__init__()始终logging在案,您可以在conf.py中使用autodoc-skip-member。 喜欢这个:def skip(app, what, name, obj, skip, options): if name == "__init__": return False return skip def setup(app): app.connect("autodoc-skip-member", skip)这明确定义
__init__不被跳过(默认情况下是这样)。 这个configuration被指定一次,并且不需要为.rst源中的每个类添加任何额外的标记。 - 
Sphinx 1.1中增加了
special-members选项。 它使得“特殊”成员(像__special__这样的__special__)被autodoclogging下来。自狮身人面像1.2以来,这个选项的参数使它比以前更有用。
 - 
使用
automethod:.. autoclass:: MyClass :members: .. automethod:: __init__必须为每个类添加(不能与
automodule一起使用,正如在此答案的第一个修订版的注释中指出的那样)。 
 你很近 您可以在conf.py文件中使用autoclass_content选项: 
 autoclass_content = 'both' 
 在过去几年中,我为各种不相关的Python项目编写了autodoc-skip-membercallbackautodoc-skip-member几个变体,因为我希望像__init__() , __enter__() __exit__()和__exit__()这样的方法出现在我的API文档中(毕竟,这些“特殊方法”是API的一部分,比在特殊方法的文档string中更好地logging它们)。 
最近我采取了最好的实现,并将其作为我的一个Python项目的一部分( 这里是文档 )。 实现基本上归结为:
 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 (ie 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 
 是的,有更多的文件比逻辑:-)。 通过使用special-members选项来定义autodoc-skip-membercallback(对我来说)的好处是, special-members选项还可以启用像__weakref__这样的属性的文档(所有新样式类AFAIK )我认为是噪音,根本没用。 callback方法避免了这一点(因为它只能在函数/方法上工作,而忽略其他属性)。