dea*_*mon 54 python documentation
在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 {}
Run Code Online (Sandbox Code Playgroud)
但是如何在API文档中记录字段或属性以供使用help?
Eli*_*sky 62
Python有一个定义Docstring约定的PEP(257).关于属性的文档,它指出:
在模块,类或
__init__方法的顶层进行简单赋值后立即出现的字符串文字称为"属性docstrings".
因此,以下内容被视为文档属性:
class Foo(object):
velocity = 1
"""Foo's initial velocity - class variable"""
def __init__(self, args):
self.location = 0.0
"""Foo's initial location - instance variable"""
Run Code Online (Sandbox Code Playgroud)
(编辑:修复了第二个文档字符串)
使用帮助的python解释器中的属性文档对我来说很好,请参阅proprerty文档.注:IPython中的魔法帮助运营商?,并没有显示属性文档字符串.
>>> class foo(object):
>>> def __init__(self, bar):
>>> self._bar = bar
>>> @property
>>> def bar(self):
>>> """bar property"""
>>> return self._bar
>>> help(foo.bar)
Help on property:
bar property
Run Code Online (Sandbox Code Playgroud)
在Sphinx中,您必须使用该:members:指令来记录属性,请参阅autodoc文档.对我来说就像一个魅力!
如果:members:使用Sphinx,也会记录属性.属性的文档字符串可以作为属性之前的注释给出,但在哈希标记EG后面使用冒号#: the foo attribute.从Sphinx autodoc文档:
对于模块数据成员和类属性,可以将文档放入具有特殊格式的注释中(使用#:启动注释而不是#),或者在定义后的docstring中.注释在定义之前需要在它们自己的行上,或者在同一行上的赋值之后立即.后一种形式仅限于一行.
在类 docstring 中记录可自由访问的属性或将它们放入属性中。您正在正确记录属性,问题可能出在 2.x 和旧式类中,它们不支持object在这种情况下继承的描述符 \xe2\x80\x94 。