我知道我可以使用“help()”来查看包中现有的帮助信息。但是在我写了自己的函数/类之后,我怎样才能启用“帮助”来查看帮助文档呢?我知道“comment”的第一行是 doc 属性,但这不是我想要的。
我希望编译出自己的包,其他人可以从"help()"中看到。如何做到这一点?
最佳答案
help()
完全基于 __doc__
属性(以及函数参数的内省(introspection)),因此请确保您的模块、类和函数都有文档字符串。
文档字符串不是注释,它是顶部的裸字符串文字:
"""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
模块有一个docstring:
>>> 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()
直接呈现,连同模块内容(以及递归地,内容文档字符串):
>>> 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
[...]
关于python - 如何将我自己的 "help"信息添加到 python 函数/类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40891380/