Python help() 函数用于获取指定的模块、类、函数、变量等的文档,这种方法通常与 python 解释器控制台一起使用,以获取有关 python 对象的详细信息。
Python 帮助() 函数
Python 帮助() 函数语法是:
1help([object])
If no argument is given, the interactive help system starts on the interpreter console. In python help console, we can specify module, class, function names to get their help documentation. Some of them are:
1help> True
2
3help> collections
4
5help> builtins
6
7help> modules
8
9help> keywords
10
11help> symbols
12
13help> topics
14
15help> LOOPING
如果您想离开帮助控制台,请键入quit
,我们也可以通过将参数传输到 help() 函数来直接从 python 控制台获取帮助文档。
1>>> help('collections')
2
3>>> help(print)
4
5>>> help(globals)
让我们来看看 globals()函数的 help() 函数的输出是什么。
1>>> help('builtins.globals')
2
3Help on built-in function globals in builtins:
4
5builtins.globals = globals()
6 Return the dictionary containing the current scope's global variables.
7
8 NOTE: Updates to this dictionary *will* affect name lookups in the current global scope and vice-versa.
定义用于自定义类别和函数的 help()
我们可以通过定义 docstring (文档字符串) 来定义 help() 函数输出,以定义我们的自定义类和函数。 默认情况下,方法的体内第一个评论字符串被用作其 docstring。 它被三个双引文包围。 假设我们有一个 python 文件 python_help_examples.py
与以下代码。
1def add(x, y):
2 """
3 This function adds the given integer arguments
4 :param x: integer
5 :param y: integer
6 :return: integer
7 """
8 return x + y
9
10class Employee:
11 """
12 Employee class, mapped to "employee" table in Database
13 """
14 id = 0
15 name = ''
16
17 def __init__(self, i, n):
18 """
19 Employee object constructor
20 :param i: integer, must be positive
21 :param n: string
22 """
23 self.id = i
24 self.name = n
请注意,我们已经为函数,类和它的方法定义了docstring。 您应该遵循一些文档格式,我已经使用PyCharm IDE自动生成了一些部分。 NumPy docstring guide是一个很好的地方,可以得到一些关于正确的方式帮助文档的想法。 让我们看看如何在python控制台中获得这个docstring作为帮助文档。 首先,我们需要在控制台中执行这个脚本来加载我们的函数和类定义。
1>>> exec(open("python_help_examples.py").read())
我们可以通过 globals() 命令验证函数和类定义是否存在。
1>>> globals()
2{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__warningregistry__': {'version': 0}, 'add': <function add at 0x100dda1e0>, 'Employee': <class '__main__.Employee'>}
请注意,员工
和添加
在全球范围字典中存在,现在我们可以使用 help() 函数获取帮助文档。
1>>> help('python_help_examples')
1>>> help('python_help_examples.add')
2
3Help on function add in python_help_examples:
4
5python_help_examples.add = add(x, y)
6 This function adds the given integer arguments
7 :param x: integer
8 :param y: integer
9 :return: integer
10(END)
1>>> help('python_help_examples.Employee')
1>>> help('python_help_examples.Employee.__init__')
2
3Help on function __init__ in python_help_examples.Employee:
4
5python_help_examples.Employee.__init__ = __init__(self, i, n)
6 Employee object constructor
7 :param i: integer, must be positive
8 :param n: string
9(END)
摘要
Python help() 函数非常有用,以获取有关模块、类和函数的详细信息. 始终是最佳做法来定义自定义类和函数的 docstring 来解释它们的使用。
您可以从我们的 GitHub 存储库中查阅完整的 Python 脚本和更多 Python 示例。
参考: 官方文件