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

Tan*_*guy 44 python docstring

我无法弄清楚print(__doc__)脚本开头的操作是什么,就像在这个Scikit示例中一样.

我一直在谷歌中寻找Python文档字符串,__doc__函数中提供一些文档似乎很有用.但我看不到__doc__脚本中间做了什么.

And*_*ini 74

__doc__在函数中提供一些文档似乎很有用

这是真的.除功能外,还可以在模块中提供文档.所以,如果你有一个这样命名的文件mymodule.py:

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

def f(x):
    """This is the function docstring."""
    return 2 * x
Run Code Online (Sandbox Code Playgroud)

您可以像这样访问其文档字符串:

>>> import mymodule
>>> mymodule.__doc__
'This is the module docstring.'
>>> mymodule.f.__doc__
'This is the function docstring.'
Run Code Online (Sandbox Code Playgroud)

现在,回到你的问题:做print(__doc__)什么?简单地说:它打印模块docstring.如果未指定docstring,则__doc__默认为None.


Mar*_*ers 16

以字符串文字开头的任何函数,类或模块都是非空的__doc__; 该初始字符串作为文档字符串; None如果没有这样的字符串,它将被设置为.请参阅Python词汇表中的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>`.

"""
Run Code Online (Sandbox Code Playgroud)

print(__doc__)每次运行脚本时,该命令只是重复使用该文档字符串将其写入终端,而任何其他python工具(例如交互式解释器help()函数)都可以内省相同的值.