我知道我可以使用「help()」來查看包中的現有幫助信息。但是在我編寫自己的函數/類後,如何啓用「幫助」來查看幫助文檔?我知道「評論」的第一行是doc屬性,但這不是我想要的。如何將我自己的「幫助」信息添加到Python函數/類?
我希望自己編譯包,其他人可以從「help()」中看到。怎麼做?
我知道我可以使用「help()」來查看包中的現有幫助信息。但是在我編寫自己的函數/類後,如何啓用「幫助」來查看幫助文檔?我知道「評論」的第一行是doc屬性,但這不是我想要的。如何將我自己的「幫助」信息添加到Python函數/類?
我希望自己編譯包,其他人可以從「help()」中看到。怎麼做?
help()
完全基於__doc__
屬性(和函數參數的自省),所以請確保您的模塊,您的類和您的函數都有一個文檔字符串。
文檔字符串不一個評論,它是在頂部裸露的字符串字面權:
"""This is a module docstring, shown when you use help() on a module"""
class Foo:
"""Help for the class Foo"""
def bar(self):
"""Help for the bar method of Foo classes"""
def spam(f):
"""Help for the spam function"""
例如,流行的第三方requests
模塊有一個文檔字符串:
>>> import requests
>>> requests.__doc__
'\nRequests HTTP library\n~~~~~~~~~~~~~~~~~~~~~\n\nRequests is an HTTP library, written in Python, for human beings. Basic GET\nusage:\n\n >>> import requests\n >>> r = requests.get(\'https://www.python.org\')\n >>> r.status_code\n 200\n >>> \'Python is a programming language\' in r.content\n True\n\n... or POST:\n\n >>> payload = dict(key1=\'value1\', key2=\'value2\')\n >>> r = requests.post(\'http://httpbin.org/post\', data=payload)\n >>> print(r.text)\n {\n ...\n "form": {\n "key2": "value2",\n "key1": "value1"\n },\n ...\n }\n\nThe other HTTP methods are supported - see `requests.api`. Full documentation\nis at <http://python-requests.org>.\n\n:copyright: (c) 2016 by Kenneth Reitz.\n:license: Apache 2.0, see LICENSE for more details.\n'
它由help()
直接呈現,連同模塊內容(以及遞歸的內容docstrings):
>>> help('requests')
Help on package requests:
NAME
requests
DESCRIPTION
Requests HTTP library
~~~~~~~~~~~~~~~~~~~~~
Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:
>>> import requests
>>> r = requests.get('https://www.python.org')
>>> r.status_code
200
[...]
你可以使用argparse:https://docs.python.org/2/howto/argparse.html。它允許您創建一個可以自定義的--help
參數以及添加參數描述。
例子:
parser = argparse.ArgumentParser(description = "Write your help documentation here...")
parser.add_argument('config.txt', nargs='?', help='Write about your positional arguments here')
args = parser.parse_args()
因此,當有人與--help
運行您的程序將輸出:
$python yourProgram.py --help
usage: yourProgram.py [-h] [config.txt]
Write your help documentation here...
positional arguments:
config.txt Write about your positional arguments here
optional arguments:
-h, --help show this help message and exit