探索 Python 中 `help()` 函数的特性
Python help()
函数的特性
Trey Hunner 10 分钟阅读 • Python 3.9—3.13 • 2025 年 3 月 3 日
分享
已将 https://pym.dev/help-features/ 复制到剪贴板。
Python 有一个内置的 help
函数,用于获取帮助...但是 help
可以 做 什么呢?
help
函数可以用于查找以下内容的文档:
- 函数
- 模块
- 任何对象
- 符号
- 关键字
- 主题
让我们来看看 help
的所有 6 种用法。我们将从最常见的 3 种用法开始:函数、模块和所有其他对象。
传递对象给 help
我几乎总是通过传递一个对象给 help
函数来使用它:可以是一个函数、模块、类或者类实例。
传递一个函数对象 (是的,函数在 Python 中是对象) 给 help(...)
将会显示该函数的 docstring:
>>> help(print)
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
传递一个类或者一个类的实例将会显示该类的 docstring,以及类中每个方法的文档:
>>> numbers = [2, 1, 3, 4]
>>> help(numbers)
Help on list object:
class list(object)
| list(iterable=(), /)
|
| Built-in mutable sequence.
|
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
... [此处显示了更多方法]
传递一个模块对象将会显示模块内所有内容的文档:
>>> import math
>>> help(math)
Help on module math:
NAME
math
MODULE REFERENCE
https://docs.python.org/3.13/library/math.html
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
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.
The result is between 0 and pi.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
... [此处显示了更多函数,以及数据属性]
你也可以将方法对象 (方法 只是附加到类的函数) 或者模块中的函数传递给 help
:
>>> help(numbers.pop)
Help on built-in function pop:
pop(index=-1, /) method of builtins.list instance
Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
>>> help(math.sqrt)
Help on built-in function sqrt in module math:
sqrt(x, /)
Return the square root of x.
还有其他使用 help
函数的方法,但是在深入研究这些方法之前,我想先讨论一下上面输出中显示的 *
和 /
符号。
补充:键盘快捷键
一旦你 进入 help
,如何移动呢? 另外,如何退出 help
?
help
函数在不同的平台上支持不同的键盘快捷键,这有点不幸。
在 Windows 上,Python help
函数通常使用 more 命令。 在 Linux 和 Mac 上,它使用 less 命令。
在 Linux 和 Mac 上,要知道的最有用的 help
键盘快捷键是:
Down
或j
:一次向下滚动一行Up
或k
:一次向上滚动一行Ctrl-D
:向下滚动半个屏幕Ctrl-U
:向上滚动半个屏幕/
:在当前帮助页面内向下搜索?
:在当前帮助页面内向上搜索q
:退出帮助
在 Windows 上,要知道的最有用的 help
键盘快捷键是:
Enter
:一次向下滚动一行Space
:向下滚动半个屏幕q
:退出
Python 使用的 more
程序或 less
程序(取决于你的操作系统)称为“分页器”。 如果你碰巧安装了一个更高级的分页器程序,你可以设置你的 PAGER
或 MANPAGER
环境变量来自定义使用的分页器程序。
获取关于字符串的帮助
help
函数将接受任何对象并返回关于该对象的帮助。但是 help
函数也接受字符串:
>>> help("math.prod")
Help on built-in function prod in math:
math.prod = prod(iterable, /, *, start=1)
Calculate the product of all the elements in the input iterable.
The default start value for the product is 1.
When the iterable is empty, return the start value. This function is
intended specifically for use with numeric values and may reject
non-numeric types.
这对于获取尚未导入到你的 Python REPL 中的实用程序的帮助非常方便。
但是这也意味着我们不能将字符串传递给 help,并期望看到关于 str
类型的帮助:
>>> name = "Trey"
>>> help(name)
No Python documentation found for 'Trey'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.
要获取关于字符串的帮助,你需要传入字符串类,而不是字符串实例:
>>> 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'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
... [此处显示了更多方法]
查找符号、关键字和主题
传递给 help 的字符串不一定需要代表 Python 对象的路径。 help
函数还接受代表符号、关键字和主题的字符串。
查找符号的帮助
由于符号不是 Python 中的对象,因此不能将其作为参数传递给 help
:
>>> help(**)
File "<unknown>", line 1
help(**)
^
SyntaxError: invalid syntax
要查找符号的帮助,你可以将一个字符串传递给 help
函数。 例如,这里我们正在查找 **
运算符的作用:
>>> help("**")
The power operator
******************
The power operator binds more tightly than unary operators on its
left; it binds less tightly than unary operators on its right. The
syntax is:
power ::= (await_expr | primary) ["**" u_expr]
Thus, in an unparenthesized sequence of power and unary operators, the
operators are evaluated from right to left (this does not constrain
the evaluation order for the operands): "-1**2" results in "-1".
The power operator has the same semantics as the built-in "pow()"
function, when called with two arguments: it yields its left argument
raised to the power of its right argument. The numeric arguments are
first converted to a common type, and the result is of that type.
For int operands, the result has the same type as the operands unless
the second argument is negative; in that case, all arguments are
converted to float and a float result is delivered. For example,
"10**2" returns "100", but "10**-2" returns "0.01".
Raising "0.0" to a negative power results in a "ZeroDivisionError".
Raising a negative number to a fractional power results in a "complex"
number. (In earlier versions it raised a "ValueError".)
This operation can be customized using the special "__pow__()" and
"__rpow__()" methods.
Related help topics: EXPRESSIONS, OPERATORS
查找关键字的帮助
关键字是不能用作有效的 Python 变量名的单词。
例如,class
、if
、for
和 return
是 Python 语法中使用的关键字。 尝试将这些关键字传递给 help
将导致 SyntaxError
:
>>> help(return)
File "<python-input-0>", line 1
help(return)
^^^^^^
SyntaxError: invalid syntax
与符号类似,你可以通过将关键字作为字符串传递给 help
函数来获得关于关键字的帮助:
>>> help("if")
The "if" statement
******************
The "if" statement is used for conditional execution:
if_stmt ::= "if" assignment_expression ":" suite
("elif" assignment_expression ":" suite)*
["else" ":" suite]
It selects exactly one of the suites by evaluating the expressions one
by one until one is found to be true (see section Boolean operations
for the definition of true and false); then that suite is executed
(and no other part of the "if" statement is executed or evaluated).
If all expressions are false, the suite of the "else" clause, if
present, is executed.
Related help topics: TRUTHVALUE
查找主题的帮助
你可能已经注意到一些帮助文档底部列出了“相关帮助主题”。 要获得关于其中一个主题的帮助,请将其中一个主题传递给 help
函数:
>>> help("TRUTHVALUE")
Truth Value Testing
*******************
Any object can be tested for truth value, for use in an "if" or
"while" condition or as operand of the Boolean operations below.
By default, an object is considered true unless its class defines
either a "__bool__()" method that returns "False" or a "__len__()"
method that returns zero, when called with the object. [1] Here are
most of the built-in objects considered false:
* constants defined to be false: "None" and "False"
* zero of any numeric type: "0", "0.0", "0j", "Decimal(0)",
"Fraction(0, 1)"
* empty sequences and collections: "''", "()", "[]", "{}", "set()",
"range(0)"
Operations and built-in functions that have a Boolean result always
return "0" or "False" for false and "1" or "True" for true, unless
otherwise stated. (Important exception: the Boolean operations "or"
and "and" always return one of their operands.)
Related help topics: if, while, and, or, not, BASICMETHODS
主题始终以 ALLUPPERCASE 拼写,以将它们与关键字、符号等区分开来。
元帮助
想知道有哪些主题可以寻求帮助吗? 询问关于“topics”的帮助:
>>> help("topics")
Here is a list of available topics. Enter any topic name to get more help.
ASSERTION DELETION LOOPING SHIFTING
ASSIGNMENT DICTIONARIES MAPPINGMETHODS SLICINGS
ATTRIBUTEMETHODS DICTIONARYLITERALS MAPPINGS SPECIALATTRIBUTES
ATTRIBUTES DYNAMICFEATURES METHODS SPECIALIDENTIFIERS
AUGMENTEDASSIGNMENT ELLIPSIS MODULES SPECIALMETHODS
BASICMETHODS EXCEPTIONS NAMESPACES STRINGMETHODS
BINARY EXECUTION NONE STRINGS
BITWISE EXPRESSIONS NUMBERMETHODS SUBSCRIPTS
BOOLEAN FLOAT NUMBERS TRACEBACKS
CALLABLEMETHODS FORMATTING OBJECTS TRUTHVALUE
CALLS FRAMEOBJECTS OPERATORS TUPLELITERALS
CLASSES FRAMES PACKAGES TUPLES
CODEOBJECTS FUNCTIONS POWER TYPEOBJECTS
COMPARISON IDENTIFIERS PRECEDENCE TYPES
COMPLEX IMPORTING PRIVATENAMES UNARY
CONDITIONAL INTEGER RETURNING UNICODE
CONTEXTMANAGERS LISTLITERALS SCOPING
CONVERSIONS LISTS SEQUENCEMETHODS
DEBUGGING LITERALS SEQUENCES
要查看可以寻求帮助的符号,请将“symbols”传递给 help
:
>>> help("symbols")
Here is a list of the punctuation symbols which Python assigns special meaning
to. Enter any symbol to get more help.
!= + <= __
" += <> `
""" , == b"
% - > b'
%= -= >= f"
& . >> f"
&= ... >>= f'
' / @ j
''' // J r"
( //= [ r'
) /= \ u"
* : ] u'
** < ^ |
**= << ^= |=
*= <<= _ ~
同样的事情也适用于“keywords”:
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
如果你寻求“modules”的帮助,你也会看到所有已安装模块的列表,你可以寻求帮助:
>>> help("modules")
Python 会导入它能找到的每个模块以收集该信息,因此第一次在 Python 进程中运行 help("modules")
时,Python 通常需要一秒钟来发现和导入所有模块。
“help utility”
不确定你想要什么帮助? 如果你在不带任何参数的情况下调用 help
函数,你将进入“help utility”。
>>> help()
Welcome to Python 3.13's help utility! If this is your first time using
Python, you should definitely check out the tutorial at
https://docs.python.org/3.13/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To get a list of available
modules, keywords, symbols, or topics, enter "modules", "keywords",
"symbols", or "topics".
Each module also comes with a one-line summary of what it does; to list
the modules whose name or summary contain a given string such as "spam",
enter "modules spam".
To quit this help utility and return to the interpreter,
enter "q", "quit" or "exit".
help>
注意:从 Python 3.13 开始,你可以输入不带任何括号的 help
来启动相同的 utility。
从 help utility 中,你可以输入你想要获得帮助的事物的名称。
help
函数接受的任何字符串都可以在此 help>
提示符下提供,以查看其文档。
你经常会发现该字符串没有帮助。 例如,functions
没有帮助:
help> functions
No Python documentation found for 'functions'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.
如果你从 help utility 中键入 help
,你可以再次看到初始提示,该提示指出 modules
、keywords
、symbols
和 topics
是你可以用来发现 help
将接受哪些可能字符串的顶级类别:
help> help
Welcome to Python 3.13's help utility! If this is your first time using
Python, you should definitely check out the tutorial at
https://docs.python.org/3.13/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To get a list of available
modules, keywords, symbols, or topics, enter "modules", "keywords",
"symbols", or "topics".
Each module also comes with a one-line summary of what it does; to list
the modules whose name or summary contain a given string such as "spam",
enter "modules spam".
To quit this help utility and return to the interpreter,
enter "q", "quit" or "exit".
没有网络连接?你仍然可以使用 help
!
当我们有搜索引擎时,为什么要使用 help
函数?
好吧,如果你在没有网络连接的情况下被困了几个小时,help
函数会非常方便。
另外,如果你发现自己处于 Python REPL 或 PDB 会话 中,并且想知道特定对象是如何工作的,help
对于内省对象非常有用。 你可能还想查看 type
、dir
和 vars
函数以 内省 Python 对象。
有关如何解读在 help
输出中的函数定义中看到的各种符号的更多信息,请参阅 理解 Python 中的 help
。
每周一个 Python 技巧
需要填补你的 Python 技能中的空白吗?
注册我的 Python 时事通讯,我每周分享我最喜欢的 Python 技巧之一。
网站 获取每周 Python 技巧