Python help() 语法
help() 是 Python 的一个内置函数,它用于查看对象(包括模块、函数、类、方法、关键字等)的帮助信息(包括语法、功能等)。
语法:
help(object)说明:
help() 函数接收单个参数。
object(可选):可以是模块名、函数名、类名、方法名、关键字或字符串形式的名称。如果 object 省略,则会进入交互式帮助系统,可以通过输入 “q” 或 “quit” 退出。
提示:
- help() 函数是 pydoc 模块的包装器,因此它能够从对象的 docstring(文档字符串)中提取信息。
- 对于初学的小伙伴来说,help() 是一个非常棒的学习工具,可以随时查看不熟悉的函数或类的用法。
Python help() 摘要
| 使用频率 | 中 |
|---|---|
| 官方文档 | 查看 |
| 相关函数 | dir() |
Python help() 示例
接下来,我们通过几个简单的例子来讲解一下 Python help() 函数是如何使用的。
示例 1: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.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.分析:
使用 help() 函数可以直接输出结果,而不需要多此一举使用 print() 函数(虽然这样也没有问题)。下面两种方式都是可行的:
# 方式 1(推荐)
help(math)
# 方式 2(不推荐)
print(help(math))示例 2:help() 查看内置函数
help(round)运行结果如下。
Help on built-in function round in module builtins:
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.示例 3:help() 查看模块中的函数
import math
help(math.pow)运行结果如下。
Help on built-in function pow in module math:
pow(x, y, /)
Return x**y (x to the power of y).分析:
从结果可以看出,pow() 是 math 模块内置的一个 “函数”,而不是一个 “方法”。
示例 4:help() 查看类
help(str)运行结果如下。
Help on class str in module builtins:
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to 'utf-8'.
| errors defaults to 'strict'.
|
-- More --分析:
通过 help(str),我们可以查看类的构造方法、成员方法以及继承关系。
示例 5:help() 查看方法
help('lvyenet'.upper)运行结果如下。
Help on built-in function upper:
upper() method of builtins.str instance
Return a copy of the string converted to uppercase.分析:
通过实例方法可以直接定位方法的帮助文档,而不需要导入该模块。
示例 6:help() 查看自定义函数
def add(a, b):
'返回两个数字的和'
return a + b
help(add)运行结果如下。
Help on function add in module __main__:
add(a, b)
返回两个数字的和示例 7:help() 不带参数
help()运行结果如下。
Welcome to Python 3.12's help utility!
……
help>分析:
当 help() 函数不带任何参数时,表示进入交互式帮助模式。在该模式下,我们可以输入任何 Python 语句,程序会返回它们的帮助信息。此外,我们也可以输入 “quit” 这个命令来退出交互式帮助模式。
常见问题
1. 如何快速查看对象属性列表?
我们可以先使用 dir(obj) 列出对象都有哪些属性,然后再通过 help(obj.attr) 查看具体的属性。
2. 如何直接读取文档字符串?
我们可以使用 print(obj.__doc__),不过这种方式的格式不如 help() 友好。
3. 交互模式中如何搜索模块?
我们可以输入 “modules” 关键字可以过滤模块。比如,“modules math” 列出包含 "math" 的模块。
