Python help()函数
时间:2020-02-23 14:42:47 来源:igfitidea点击:
Python help()函数用于获取指定模块,类,函数,变量等的文档。
此方法通常与python解释器控制台一起使用,以获取有关python对象的详细信息。
Python help()函数
Python help()函数语法为:
help([object])
如果未提供任何参数,则交互式帮助系统将在解释器控制台上启动。
在python帮助控制台中,我们可以指定模块,类,函数名称以获取其帮助文档。
他们之中有一些是:
help> True help> collections help> builtins help> modules help> keywords help> symbols help> topics help> LOOPING
如果您想退出帮助控制台,请输入quit
。
通过将参数传递给help()函数,我们还可以直接从python控制台获取帮助文档。
>>> help('collections') >>> help(print) >>> help(globals)
让我们看看globals()函数的help()函数的输出是什么。
>>> help('builtins.globals') Help on built-in function globals in builtins: builtins.globals = globals() Return the dictionary containing the current scope's global variables. NOTE: Updates to this dictionary *will* affect name lookups in the current global scope and vice-versa.
定义自定义类和函数的help()
我们可以通过定义docstring(文档字符串)来为自定义类和函数定义help()函数输出。
默认情况下,方法主体中的第一个注释字符串用作其文档字符串。
它用三个双引号引起来。
假设我们有一个包含以下代码的python文件python_help_examples.py。
def add(x, y): """ This function adds the given integer arguments :param x: integer :param y: integer :return: integer """ return x + y class Employee: """ Employee class, mapped to "employee" table in Database """ id = 0 name = '' def __init__(self, i, n): """ Employee object constructor :param i: integer, must be positive :param n: string """ self.id = i self.name = n
注意,我们已经为函数,类及其方法定义了docstring。
您应该遵循某种格式的文档,我已经使用PyCharm IDE自动生成了其中的一部分。
NumPy文档字符串教程是了解正确的帮助文档方式的好地方。
让我们看看如何在python控制台中获取此文档字符串作为帮助文档。
首先,我们将必须在控制台中执行此脚本以加载函数和类定义。
我们可以使用exec()
命令来做到这一点。
>>> exec(open("python_help_examples.py").read())
我们可以使用globals()命令验证函数和类定义是否存在。
>>> globals() {'__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()函数获取帮助文档。
让我们看一些例子。
>>> help('python_help_examples')
>>> help('python_help_examples.add') Help on function add in python_help_examples: python_help_examples.add = add(x, y) This function adds the given integer arguments :param x: integer :param y: integer :return: integer (END)
>>> help('python_help_examples.Employee')
>>> help('python_help_examples.Employee.__init__') Help on function __init__ in python_help_examples.Employee: python_help_examples.Employee.__init__ = __init__(self, i, n) Employee object constructor :param i: integer, must be positive :param n: string (END)