一,什么是docstring
docstring是一个字符串文字,它作为模块,函数,类或方法定义中的第一条语句出现。这样的文档字符串会成为该对象的
__doc__
属性。
——PEP 257 – Docstring Conventions
通常,所有模块都应具有文档字符串,并且模块导出的所有函数和类也应具有文档字符串。 公共方法(包括__init__构造函数)也应具有文档字符串。 软件包可以记录在软件包目录的_init_.py文件的文档字符串中。
Python代码中其他地方出现的字符串文字也可以用作文档。 它们无法被Python字节码编译器识别,并且不能作为运行时对象属性访问,但是软件工具可以提取两种类型的额外docstring:
- 在模块,类或__init__方法的顶级进行简单赋值后立即出现的字符串文字称为“属性文档字符串”。
- 紧随另一个文档字符串之后出现的字符串文字称为“其他文档字符串”。
为了保持一致,请始终在文档字符串前后使用"""三重双引号"""
。 如果您在文档字符串中使用任何反斜杠,请使用r””“原始三重双引号”””。 对于Unicode文档字符串,请使用u””“Unicode三引号字符串”””。
二,单行Docstrings
def kos_root():
"""Return the pathname of the KOS root directory."""
global _kos_root
if _kos_root: return _kos_root
...
1,即使字符串只有一行,也要使用三重引号。这使得以后很容易扩展它。
2,结束引号与开始引号在同一行。对于一行程序,这看起来更好。
3,在文档字符串之前或之后都没有空行。
4,文档字符串是一个以句点结尾的短语。它将函数或方法的效果规定为命令(“做这个”、“返回那个”),而不是描述,例如,不要写“返回路径名…”。
5,单行文档字符串不应该是重复函数/方法参数(可以通过自省获得)的“签名”。例如:
def function(a, b):
"""function(a, b) -> list"""
- 内省
introspection
,是在运行时进行的一种对象检测机制,我们可以通过内省来获取一个对象的所有信息,比如使用dir()查看对象的属性与方法、使用type()查看对象的类型等操作。
上面这种反例类型的文档字符串仅适用于无法自省的C函数(例如内置函数)。但是,返回值的性质无法通过内省来确定,因此应予以提及。 此类文档字符串的首选形式为:
def function(a, b):
"""Do X and return a list."""
三,多行Docstrings
脚本(独立程序)的文档字符串应可用作其“使用情况”的消息,在使用不正确或缺少参数(或者可能使用“ -h”选项表示“帮助”)调用脚本时打印。 这样的文档字符串应记录脚本的功能和命令行语法,环境变量和文件。 使用情况消息可能非常详尽(几个屏幕已满),并且对于新用户而言,足以正确使用该命令,并且对于高级用户而言,它是对所有选项和参数的完整快速参考。
模块的文档字符串通常应列出该模块导出的类、异常和函数(以及任何其他对象),并以每行的一行摘要显示(这些摘要所提供的详细信息通常少于对象的文档字符串中的摘要行)。包的文档字符串(即程序包的_init_.py模块的文档字符串)也应列出该程序包导出的模块和子程序包。
函数或方法的文档字符串应总结其行为,并记录其参数,返回值,副作用,引发的异常以及何时可以调用它的限制(所有这些均适用)。 应该指出可选参数。 应该记录关键字参数是否是接口的一部分。
类的文档字符串应总结其行为,并列出公共方法和实例变量。 如果该类打算被子类化,并且具有子类的附加接口,则该接口应单独列出(在文档字符串中)。 类构造函数的__init__方法应记录在文档字符串中。 各个方法应使用自己的文档字符串记录。
如果一个类继承了另一个类,并且其行为主要是从该类继承的,则其文档字符串应提及这一点并总结差异。 使用动词“ override”来表示子类方法代替了超类方法,并且不调用超类方法; 使用动词“ extend”表示子类方法(除了其自身的行为之外)还会调用超类方法。
不要在运行文本中使用大写提及函数或方法的参数。 Python区分大小写,并且参数名称可用于关键字参数,因此文档字符串应记录正确的参数名称。 最好在单独的行上列出每个参数。 例如:
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0:
return complex_zero
...
四,处理文档缩进
Docstring处理工具将从docstring的第二行和其他行中去除均匀的缩进量,即第一行之后所有非空白行的最小缩进量。
文档字符串第一行中的任何缩进都可以忽略不计,但要保留文档字符串中后面几行的相对缩进。
应从文档字符串的开头和结尾删除空白行。
在实际编码历史中,逐渐形成了多派Docstrings风格,它们各有优点。
五,几种流行的Docstrings风格
reST风格:PEP 287 – reStructuredText Docstring Format
这也是pycharm默认的风格:
google风格:Comments and Docstrings
numpy风格:Example NumPy Style Python Docstrings
例如:
def array(p_object, dtype=None, copy=True, order='K', subok=False, ndmin=0): # real signature unknown; restored from __doc__
"""
array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
Create an array.
Parameters
----------
object : array_like
An array, any object exposing the array interface, an object whose
__array__ method returns an array, or any (nested) sequence.
dtype : data-type, optional
The desired data-type for the array. If not given, then the type will
be determined as the minimum type required to hold the objects in the
sequence.
copy : bool, optional
If true (default), then the object is copied. Otherwise, a copy will
only be made if __array__ returns a copy, if obj is a nested sequence,
or if a copy is needed to satisfy any of the other requirements
(`dtype`, `order`, etc.).
order : {'K', 'A', 'C', 'F'}, optional
Specify the memory layout of the array. If object is not an array, the
newly created array will be in C order (row major) unless 'F' is
specified, in which case it will be in Fortran order (column major).
If object is an array the following holds.
===== ========= ===================================================
order no copy copy=True
===== ========= ===================================================
'K' unchanged F & C order preserved, otherwise most similar order
'A' unchanged F order if input is F and not C, otherwise C order
'C' C order C order
'F' F order F order
===== ========= ===================================================
When ``copy=False`` and a copy is made for other reasons, the result is
the same as if ``copy=True``, with some exceptions for `A`, see the
Notes section. The default order is 'K'.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
ndmin : int, optional
Specifies the minimum number of dimensions that the resulting
array should have. Ones will be pre-pended to the shape as
needed to meet this requirement.
Returns
-------
out : ndarray
An array object satisfying the specified requirements.
See Also
--------
empty_like : Return an empty array with shape and type of input.
ones_like : Return an array of ones with shape and type of input.
zeros_like : Return an array of zeros with shape and type of input.
full_like : Return a new array with shape of input filled with value.
empty : Return a new uninitialized array.
ones : Return a new array setting values to one.
zeros : Return a new array setting values to zero.
full : Return a new array of given shape filled with value.
Notes
-----
When order is 'A' and `object` is an array in neither 'C' nor 'F' order,
and a copy is forced by a change in dtype, then the order of the result is
not necessarily 'C' as expected. This is likely a bug.
Examples
--------
>>> np.array([1, 2, 3])
array([1, 2, 3])
Upcasting:
>>> np.array([1, 2, 3.0])
array([ 1., 2., 3.])
More than one dimension:
>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
[3, 4]])
Minimum dimensions 2:
>>> np.array([1, 2, 3], ndmin=2)
array([[1, 2, 3]])
Type provided:
>>> np.array([1, 2, 3], dtype=complex)
array([ 1.+0.j, 2.+0.j, 3.+0.j])
Data-type consisting of more than one element:
>>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
>>> x['a']
array([1, 3])
Creating an array from sub-classes:
>>> np.array(np.mat('1 2; 3 4'))
array([[1, 2],
[3, 4]])
>>> np.array(np.mat('1 2; 3 4'), subok=True)
matrix([[1, 2],
[3, 4]])
"""
pass
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/98117.html