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()函数非常有助于获取有关模块、类和函数的详细信息。最佳实践是为自定义类和函数定义docstring以解释它们的用法。

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

参考资料:官方文档

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