Python help() 函数
help() 是 Python 中用于获取内置函数、模块、对象等帮助信息的内置函数。
当你对某个函数或模块的使用方法有疑问时,help() 是最好的查询工具。它会显示详细的文档字符串(docstring),帮助你理解函数的功能、参数和返回值。
单词释义: help 意为"帮助",用于获取文档信息。
基本语法与参数
语法格式
help(object)
help('topic')
参数说明
- 参数 object:
- 类型: 任意对象(函数、类、模块等)
- 描述: 要获取帮助信息的对象。
- 参数 topic:
- 类型: 字符串
- 描述: 主题名称,如模块名、函数名、关键字等。
函数说明
- 返回值: 无返回值,直接在交互式环境中打印帮助信息。
- 使用场景:
- 查询函数用法
- 查询模块功能
- 学习 Python 语法
实例
示例 1:查看函数的帮助
实例
# 查看 len 函数的帮助
help(len)
# 输出:
# Help on built-in function len in module builtins:
# len(obj, /)
# Return the number of items in a container.
# 查看 print 函数的帮助
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.
# 查看某个对象的帮助
help([].append)
# 输出:
# Help on method_descriptor:
# append(self, object, /) method of builtins.list instance
# L.append(object) -> None -- append object to end
help(len)
# 输出:
# Help on built-in function len in module builtins:
# len(obj, /)
# Return the number of items in a container.
# 查看 print 函数的帮助
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.
# 查看某个对象的帮助
help([].append)
# 输出:
# Help on method_descriptor:
# append(self, object, /) method of builtins.list instance
# L.append(object) -> None -- append object to end
代码解析:
- 直接传入函数名(不需要括号)来查看帮助。
- 帮助信息包括函数签名、参数说明和功能描述。
- 对于方法,也可以通过对象来获取帮助。
示例 2:查看模块和主题的帮助
实例
# 查看模块的帮助
import os
help(os)
# 会显示 os 模块的详细文档,包括所有函数和常量的说明
# 查看特定主题
help("modules")
# 会列出所有可用的模块
help("keywords")
# 会列出 Python 的所有关键字
help("assert")
# 会显示 assert 语句的用法
import os
help(os)
# 会显示 os 模块的详细文档,包括所有函数和常量的说明
# 查看特定主题
help("modules")
# 会列出所有可用的模块
help("keywords")
# 会列出 Python 的所有关键字
help("assert")
# 会显示 assert 语句的用法
代码解析:
- 可以查看整个模块的文档。
- 使用字符串参数可以查看特定主题的帮助。
- "modules" 主题会列出所有已安装的模块。
示例 3:在脚本中使用 help
实例
# 交互式使用(最常用)
# >>> help(list)
# 会显示 list 类的所有方法
# 查看数据类型的帮助
help(int) # 整数类型
help(str) # 字符串类型
help(dict) # 字典类型
help(tuple) # 元组类型
# 查看异常的帮助
help(ZeroDivisionError)
help(ValueError)
# 查看语法帮助
help("with")
help("for")
help("if")
# >>> help(list)
# 会显示 list 类的所有方法
# 查看数据类型的帮助
help(int) # 整数类型
help(str) # 字符串类型
help(dict) # 字典类型
help(tuple) # 元组类型
# 查看异常的帮助
help(ZeroDivisionError)
help(ValueError)
# 查看语法帮助
help("with")
help("for")
help("if")
运行结果预期:
在实际交互式 Python 环境中运行上述代码,会显示详细的帮助文档。
help() 是学习 Python 最有力的工具之一,建议在日常编程中多多使用。
Python3 内置函数
点我分享笔记