Python 3 脚本中的 print(__doc__)
print(__doc__) in Python 3 script
我无法理解 print(__doc__)
在脚本开头的作用,例如 in this Scikit example。
我一直在 google 中寻找 Python docstrings,似乎 __doc__
提供一些文档很有用,比如, 职能。但是我看不到 __doc__
在脚本中间做了什么。
任何函数,class 或模块以字符串字面量开头,都有一个非空的__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>`.
"""
每次 运行 脚本和任何其他 python 工具(如交互式解释器)时,print(__doc__)
命令只是重新使用该文档字符串将其写入您的终端help()
函数,例如)可以内省相同的值。
it seems __doc__
is useful to provide some documentation in, say, functions
这是真的。除了功能之外,还可以在模块中提供文档。因此,如果您有一个名为 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
.
我无法理解 print(__doc__)
在脚本开头的作用,例如 in this Scikit example。
我一直在 google 中寻找 Python docstrings,似乎 __doc__
提供一些文档很有用,比如, 职能。但是我看不到 __doc__
在脚本中间做了什么。
任何函数,class 或模块以字符串字面量开头,都有一个非空的__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>`.
"""
每次 运行 脚本和任何其他 python 工具(如交互式解释器)时,print(__doc__)
命令只是重新使用该文档字符串将其写入您的终端help()
函数,例如)可以内省相同的值。
it seems
__doc__
is useful to provide some documentation in, say, functions
这是真的。除了功能之外,还可以在模块中提供文档。因此,如果您有一个名为 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
.