Python help() 函数是一个内置的帮助系统,可以在任何对象、类、函数或模块上调用以收集有关它的更多信息。
如果将参数传递给此函数,则会生成有关该参数的帮助页面。在这种情况下,如果未传递任何参数,则解释器控制台上会显示交互式帮助系统。该函数是内置函数之一,无需导入任何内置模块即可使用该方法。
语法
python help() 函数的语法如下 -
help(object)
参数
python help() 函数接受单个参数 -
- object − 此参数指定我们需要帮助的对象。
返回值
python help() 函数返回与传递的对象相关的信息。
help() 函数示例
练习以下示例来理解 Python 中 help() 函数的用法:
示例:使用 help() 函数
以下示例显示了 Python help() 函数的基本用法。在这里,我们将内置函数 “print()” 作为参数传递给 help() 函数,该函数将显示函数的简要描述。
help(print)
在执行上述程序时,将生成以下输出 -
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
示例:使用 help() 函数获取模块的详细信息
如果我们想显示 Python 内置模块的详细信息,我们只需导入它并将该模块作为参数值传递给 help() 函数。
import math
help(math)
以下是执行上述程序得到的输出 -
Help on built-in module math:
NAME
math
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
NAME
math
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
示例:使用 help() 函数获取类的详细信息
如果我们将类名作为参数传递给它,help() 函数会返回类的描述。它将显示所传递类的方法和其他属性。
class NewClass:
def firstExample(self):
"""
This is an example of NewClass.
"""
pass
help(NewClass)
通过执行上述程序获得以下输出 -
Help on class NewClass in module __main__:
class NewClass(builtins.object)
| Methods defined here:
|
| firstExample(self)
| This is an example of NewClass.
class NewClass(builtins.object)
| Methods defined here:
|
| firstExample(self)
| This is an example of NewClass.
示例:使用 help() 函数获取本地方法的详细信息
在 help() 函数的帮助下,我们还可以显示本地方法的描述,如下例所示。
class NewClass:
def firstExample(self):
"""
This is an example of NewClass.
"""
pass
newObj = NewClass()
help(newObj.firstExample)
上述程序在执行时显示以下输出 -
Help on method firstExample in module __main__:
firstExample() method of __main__.NewClass instance
This is an example of NewClass.
firstExample() method of __main__.NewClass instance
This is an example of NewClass.