用Python 3 scrip打印(文档)

2024-04-23 21:07:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道print(__doc__)在脚本的开头做什么,比如in this Scikit example

我一直在google中寻找Python docstrings,似乎__doc__可以在函数中提供一些文档。但我看不出__doc__在脚本中间做什么。


Tags: 函数in文档脚本docexamplegooglescikit
2条回答

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

您可以这样访问它的docstring:

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

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

任何以字符串文本开头的函数、类或模块都有一个非空的__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()函数)都可以内省该值。

相关问题 更多 >