如何将自己的“帮助”信息添加到python函数/类?

时间:2016-11-30 14:52:06

标签: python documentation

我知道我可以使用“help()”查看软件包中的现有帮助信息。但在我编写自己的函数/类之后,如何启用“帮助”来查看帮助文档?我知道“评论”的第一行是 doc 属性,但这不是我想要的。

我希望编译自己的包,其他人可以从“help()”中看到。怎么做?

2 个答案:

答案 0 :(得分:2)

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()直接呈现,与模块内容一起呈现(并递归地呈现内容文档字符串):

>>> 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
[...]

答案 1 :(得分:2)

您可以使用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