![](/img/trans.png)
[英]How print python method documentation using inspect or __doc__ method
[英]print(__doc__) in Python 3 script
我無法弄清楚print(__doc__)
在腳本開頭做了什么,就像在這個 Scikit 示例中一樣。
我一直在 google 中尋找Python 文檔字符串,似乎__doc__
在提供一些文檔方面很有用,比如,函數。 但是我看不到__doc__
在腳本中間做了什么。
似乎
__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__)
什么作用? 簡單地說:它打印模塊文檔字符串。 如果未指定 docstring,則__doc__
默認為None
。
任何以字符串文字開頭的函數、類或模塊都有一個非空的__doc__
; 該初始字符串被視為文檔字符串; 如果不存在這樣的字符串,它將被設置為None
。 請參閱 Python 詞匯表中的文檔字符串術語定義。
當您下載該 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()
函數)都可以內省相同的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.