如何在 Python 中记录字段和属性?
在 Python 中记录类或方法很容易:
class Something:
""" Description of the class. """
def do_it(self):
""" Description of the method. """
pass
class_variable = 1 # How to comment?
@property
def give_me_some_special_dict(self):
""" doesn't work! Doc of general dict will be shown. """
return {}
但是如何记录字段或属性以便在 API 文档或帮助中使用?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Python 有一个 PEP (257)定义文档字符串约定。关于属性的文档,它指出:
因此以下内容被视为记录属性:(
编辑:修复了第二个文档字符串)
Python has a PEP (257) that defines Docstring Conventions. Regarding documentation of attributes, it states:
So the following are considered documented attributes:
(Edit: Fixed second docstring)
使用帮助在 python 解释器中记录属性对我来说效果很好,请参阅 proprerty 文档< /a>. 注意:IPython 的神奇帮助运算符
?
没有显示属性文档字符串。在 Sphinx 中,您必须使用
:members:< /code> 指令到文档属性,请参阅 autodoc 文档。对我来说就像一个魅力!
如果使用
:members:
,Sphinx 也会记录属性。属性的文档字符串可以作为属性前面的注释给出,但在散列标记后面使用冒号,EG#: foo attribute
。来自 Sphinx autodoc 文档:Documentation of a property in the python interpreter using help works fine for me, see proprerty documentation. Note: IPython's magic help operator,
?
, did not display the property docstring.In Sphinx you must use the
:members:
directive to document properties, see autodoc documentation. Works like a charm for me!Attributes will also be documented by Sphinx if
:members:
is used. Docstrings for attributes can be given as comments preceding the attribute, but using a colon following the hash mark, EG#: the foo attribute
. From the Sphinx autodoc documentation:在类 docstring 中记录可自由访问的属性或将它们放入属性中。您正在正确记录属性,问题可能出在 2.x 和旧式类中,它们不支持描述符 - 在这种情况下从
object
继承。Document freely accessible attributes in the class docstring or make them into properties. You're documenting properties properly, the problem might be in 2.x and old-style classes, which don't support descriptors — inherit from
object
in that case.使用 Sphinx 表示法 / 重构文本,您可以自动从 Python 源代码生成格式良好的文档。它还支持函数的参数和返回值 - 据我所知没有字段,但您可以轻松地为它们创建一个列表。
With Sphinx notation / Restructured Text in your docstrings you can generate nicely formatted documentation from you Python sources automatically. It also supports arguments and return values for functions - no fields as far as I know, but you can easily create a list for them.