Python 3脚本中的print(__doc__)

74
我无法理解脚本开头的print(__doc__)是什么意思,例如在这个Scikit示例中
我已经在谷歌中寻找了Python文档字符串,并且似乎__doc__对于提供一些文档信息(例如函数)非常有用。但是我看不到在脚本中间__doc__的作用是什么。
2个回答

114

看起来__doc__对于在函数中提供一些文档非常有用。

这是真的。除了函数之外,文档还可以在模块中提供。因此,如果您有一个名为mymodule.py的文件如下:

"""This is the module docstring."""

def f(x):
    """This is the function docstring."""
    return 2 * x

你可以像这样访问它的文档字符串:

>>> import mymodule
>>> mymodule.__doc__
'This is the module docstring.'
>>> mymodule.f.__doc__
'This is the function docstring.'

现在回到你的问题: print(__doc__) 是什么意思?简单来说:它会打印模块的文档字符串。如果没有指定文档字符串,__doc__ 默认为 None


25

以字符串字面值开头的任何函数、类或模块都具有非空的__doc__; 初始字符串被视为文档字符串;如果没有这样的字符串,则将其设置为None。请参阅Python词汇表中的文档字符串术语定义。

当您下载该Scikit脚本示例时,您会看到它以这样的字符串开头:

"""
================================
Recognizing hand-written digits
================================

An example showing how the scikit-learn can be used to recognize images of
hand-written digits.

This example is commented in the
:ref:`tutorial section of the user manual <introduction>`.

"""

print(__doc__) 命令会简单地重复使用文档字符串并在每次运行脚本时将其写入终端,任何其他的 Python 工具(例如交互式解释器中的 help() 函数)都可以检查该相同的值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接