如何使用Python的文档字符串记录带有参数的方法?
编辑:
PEP 257给出了这样一个例子:
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
...
这是大多数Python开发人员使用的约定吗?
Keyword arguments:
<parameter name> -- Definition (default value if any)
我还以为你会更正式一点呢,比如
def complex(real=0.0, imag=0.0):
"""Form a complex number.
@param: real The real part (default 0.0)
@param: imag The imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0: return complex_zero
...
环境:Python 2.7.1
约定:
PEP 257文档字符串约定
PEP 287 reStructuredText文档字符串格式
工具:
Epydoc:为Python自动生成API文档
autodoc -包括文档字符串中的文档
PyCharm对文档字符串有一些很好的支持
更新:从Python 3.5开始,你可以使用类型提示,这是一种紧凑的、机器可读的语法:
from typing import Dict, Union
def foo(i: int, d: Dict[str, Union[str, int]]) -> int:
"""
Explanation: this function takes two arguments: `i` and `d`.
`i` is annotated simply as `int`. `d` is a dictionary with `str` keys
and values that can be either `str` or `int`.
The return type is `int`.
"""
这种语法的主要优点是它是由语言定义的,并且是明确的,因此像PyCharm这样的工具可以很容易地利用它。
约定:
PEP 257文档字符串约定
PEP 287 reStructuredText文档字符串格式
工具:
Epydoc:为Python自动生成API文档
autodoc -包括文档字符串中的文档
PyCharm对文档字符串有一些很好的支持
更新:从Python 3.5开始,你可以使用类型提示,这是一种紧凑的、机器可读的语法:
from typing import Dict, Union
def foo(i: int, d: Dict[str, Union[str, int]]) -> int:
"""
Explanation: this function takes two arguments: `i` and `d`.
`i` is annotated simply as `int`. `d` is a dictionary with `str` keys
and values that can be either `str` or `int`.
The return type is `int`.
"""
这种语法的主要优点是它是由语言定义的,并且是明确的,因此像PyCharm这样的工具可以很容易地利用它。
文档字符串只在交互环境中有用,例如Python shell。当记录那些不会被交互使用的对象(例如内部对象,框架回调)时,你最好使用常规注释。下面是我用来将缩进的注释挂在项目上的一种风格,每个注释都在自己的行上,这样你就知道注释应用于:
def Recomputate \
(
TheRotaryGyrator,
# the rotary gyrator to operate on
Computrons,
# the computrons to perform the recomputation with
Forthwith,
# whether to recomputate forthwith or at one's leisure
) :
# recomputates the specified rotary gyrator with
# the desired computrons.
...
#end Recomputate
你不能用文档字符串做这种事情。