如何在Python中记录字段和属性?

时间:2011-05-19 15:10:33

标签: 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 {}

但是如何在API文档或help中记录字段或属性以供使用?

4 个答案:

答案 0 :(得分:60)

Python有一个定义Docstring约定的PEP(257)。关于属性的文档,它声明:

  

立即发生字符串文字   在顶部进行简单的任务之后   模块,类或__init__的级别   方法称为“属性   文档字符串”

因此,以下内容被视为文档属性:

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"""   

(编辑:修复了第二个文档字符串)

答案 1 :(得分:9)

使用帮助的python解释器中的属性文档对我来说很好,请参阅proprerty documentation注意:IPython的魔术帮助操作员?确实显示属性docstring。

>>> 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

在Sphinx中,您必须使用:members:指令来记录属性,请参阅autodoc documentation。对我来说就像一个魅力!

如果使用:members:,Sphinx也会记录属性。属性的文档字符串可以作为属性之前的注释给出,但在哈希标记EG #: the foo attribute后面使用冒号。来自Sphinx autodoc文档:

  

对于模块数据成员和类属性,可以将文档放入具有特殊格式的注释中(使用#:启动注释而不是#),或者在定义后的docstring中。注释在定义之前需要在它们自己的行上,或者在同一行上的赋值之后立即。后一种形式仅限于一行。

答案 2 :(得分:3)

在类docstring中记录可自由访问的属性或将它们转换为属性。您正在正确记录属性,问题可能在2.x和旧式类(不支持描述符) - 在这种情况下从object继承。

答案 3 :(得分:2)

在文档字符串中使用Sphinx表示法/ Restructured Text,您可以自动从Python源生成格式良好的文档。它还支持函数的参数和返回值 - 据我所知,没有字段,但您可以轻松地为它们创建列表。

相关问题