在Python 3脚本中打印(__ doc __)

时间:2015-10-11 14:54:07

标签: python docstring

我无法弄清楚print(__doc__)在脚本开头做了什么,例如in this Scikit example

我一直在谷歌中寻找 Python docstrings ,似乎__doc__对于提供一些文档,例如函数很有用。但我看不出__doc__在脚本中间做了什么。

2 个答案:

答案 0 :(得分:68)

  

似乎__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

答案 1 :(得分:15)

以字符串文字开头的任何函数,类或模块都具有非空__doc__;该初始字符串作为文档字符串;如果没有这样的字符串,它将被设置为None。请参阅Python词汇表中的docstring term definition

下载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()函数)可以反省同样的价值。

相关问题