在 Python 3脚本中打印(__doc__)

我不知道 print(__doc__)在脚本的开头做了什么,比如 在这个 Scikit 的例子中

我一直在谷歌中寻找 Python 文档字符串,它似乎是有用的 __doc__提供一些文档,比如说,功能。但是我不知道 __doc__在脚本中间做什么。

68801 次浏览

任何函数,以字符串文字开头的类 或模组都有一个非空的 __doc__; 初始字符串作为文档字符串; 如果没有这样的字符串,则将其设置为 None。请参阅 Python 术语表中的 < em > docstring 术语定义

当您下载 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()函数)都可以内省相同的值。

看起来 __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__)是做什么的?简单地说: 它打印模块 docstring。如果未指定 docstring,则 __doc__默认为 None