Python 3 脚本中的 print(__doc__)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33066383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:41:53  来源:igfitidea点击:

print(__doc__) in Python 3 script

pythondocstring

提问by Tanguy

I can't figure out what does the print(__doc__)do at the beginning of a script, like in this Scikit example.

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

I have been looking for Python docstringsin google, and it seems __doc__is useful to provide some documentation in, say, functions. But I can't see what does __doc__do in the middle of a script.

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

采纳答案by Andrea Corbellini

it seems __doc__is useful to provide some documentation in, say, functions

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

This is true. In addition to functions, documentation can also be provided in modules. So, if you have a file named mymodule.pylike this:

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

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

def f(x):
    """This is the function docstring."""
    return 2 * x

You can access its docstrings like this:

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

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

Now, back to your question: what does print(__doc__)do? Simply put: it prints the module docstring. If no docstring has been specified, __doc__defaults to None.

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

回答by Martijn Pieters

Any function, class or modulestarting with a string literal has a non-empty __doc__; that initial string is taken as the documentation string; it'll be set to Noneif no such string is present. See the docstringterm definitionin the Python glossary.

任何以字符串文字开头的函数、类或模块都有一个非空的__doc__; 该初始字符串被视为文档字符串;None如果不存在这样的字符串,它将被设置为。请参阅Python 词汇表中的文档字符串术语定义

When you download that Scikit script example, you'll see it starts with such a string:

当您下载该 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>`.

"""

The print(__doc__)command simply re-uses that documentation string to write it to your terminal each time you run the script, and any other python tool (like the interactive interpreter help()function, for example) can introspect that same value.

print(__doc__)每次运行脚本时,该命令都会简单地重新使用该文档字符串将其写入终端,并且任何其他 Python 工具(例如交互式解释器help()函数)都可以内省相同的值。