Python 帮助(help())函数

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()

我们可以通过定义文档字符串(documentation string)为我们的自定义类和函数定义help()函数输出。默认情况下,方法体中的第一个注释字符串被用作其文档字符串。它被三个双引号包围。假设我们有一个名为python_help_examples.py的Python文件,其中包含以下代码。

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

请注意,我们为函数、类及其方法定义了文档字符串。您应该遵循一些文档格式,我已经使用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'>}

请注意,‘Employee’和‘add’存在于全局范围字典中。现在我们可以使用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)

总结

Python的help()函数非常有助于获取有关模块、类和函数的详细信息。为自定义类和函数定义文档字符串以解释它们的用法始终是最佳实践。

您可以从我们的GitHub代码库中查看完整的Python脚本和更多Python示例。

参考:官方文档

Source:
https://www.digitalocean.com/community/tutorials/python-help-function