【问题标题】:print(__doc__) in Python 3 scriptPython 3 脚本中的 print(__doc__)
【发布时间】:2015-10-11 14:54:06
【问题描述】:

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

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

【问题讨论】:

    标签: python docstring


    【解决方案1】:

    似乎__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__) 是做什么的?简单地说:它打印模块文档字符串。如果没有指定文档字符串,__doc__ 默认为None

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-02-08
        • 2021-05-07
        • 2023-03-27
        • 1970-01-01
        • 2012-10-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多