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

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)

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

  • 我也想知道,[和Sphinx确实](http://sphinx.pocoo.org/ext/autodoc.html#directive-autoattribute). (14认同)
  • `help`虽然没有显示这个属性文档 (6认同)
  • `help` 不显示“属性文档字符串”的此文档,因为它们在运行时不会保留。根据 [PEP 257](https://www.python.org/dev/peps/pep-0257/):“它们不被 Python 字节码编译器识别,也不能作为运行时对象属性访问(即未分配给`__doc__`)" (5认同)
  • @JosieThompson PEP 224 早在 2001 年就被“拒绝”了。PEP 257 是正确的参考。 (3认同)
  • @Jochen:这很好,因为现在Sphinx是Python文档的事实上的工具 (2认同)
  • 迟到的评论但对我来说似乎很重要:标准库 `help` 函数不显示属性文档字符串。 (2认同)

Mar*_*ski 9

使用帮助的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中.注释在定义之前需要在它们自己的行上,或者在同一行上的赋值之后立即.后一种形式仅限于一行.


Cat*_*lus 5

在类 docstring 中记录可自由访问的属性或将它们放入属性中。您正在正确记录属性,问题可能出在 2.x 和旧式类中,它们不支持object在这种情况下继承的描述符 \xe2\x80\x94 。

\n