当前位置: 首页 > news >正文

Python 常用内置函数详解(十):help()函数——查看对象的帮助信息

目录

  • 一、语法参考
  • 二、示例

一、语法参考

help() 函数的语法格式如下:

参数说明:

  1. request:可选参数,要查看其帮助信息的对象,如类、函数、模块、数据类型等;
  2. 返回值:返回对象的帮助信息。

二、示例

【示例1】查看input()函数的帮助信息。利用help()函数查看input()函数的帮助信息,示例代码如下:

help(input)  # 查看input()函数的信息

输出结果为:

Help on built-in function input in module builtins:input(prompt='', /)Read a string from standard input.  The trailing newline is stripped.The prompt string, if given, is printed to standard output without atrailing newline before reading input.If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.On *nix systems, readline is used if available.

【示例2】查看Python中所有的保留字。利用help()函数查看Python中所有的保留字,示例代码如下:

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 

【示例3】启动帮助系统。使用help()函数启动帮助系统,查看对象的帮助信息,示例代码如下:

help()  # 调用help()函数,不传入参数

输出结果如下图所示:

如果 help() 函数不传入参数,则会在解释器控制台启动帮助系统,如上图所示;在帮助系统内部输入模块名、类名、函数名、关键字等,会在控制台上显示其使用说明,输入 quit,将退出帮助系统。在 help> 后输入 keywords,Python 中所有的关键字将会显示在控制台。

【示例4】查看os模块的帮助信息。使用help()函数查看os模块的帮助信息,示例代码如下:

help('os')  # 查看os模块的帮助信息

【示例5】查看模块中指定函数的帮助信息。使用help()函数查看os.path模块中 "abspath" 函数的帮助信息,示例代码如下:

help("os.path.abspath")  # 查看os.path模块中"abspath"函数的帮助信息

输出结果为:

Help on function abspath in os.path:os.path.abspath = abspath(path)Return the absolute version of a path.

【示例6】看数据类型的帮助信息。使用help()函数查看字符类型的帮助信息,示例代码如下:

help('str')  # 查看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 sys.getdefaultencoding().|  errors defaults to 'strict'.||  Methods defined here:
........

【示例7】查看关键字的帮助信息。使用help()函数查看关键字 "if" 的帮助信息,示例代码如下:

help("if")  # 查看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

【示例8】查看错误异常的帮助信息。使用help()函数查看语法错误异常 "SyntaxError" 的帮助信息,示例代码如下:

help("SyntaxError")  # 查看语法错误"SyntaxError"的帮助信息

输出结果为:

Help on class SyntaxError in module builtins:class SyntaxError(Exception)|  Invalid syntax.||  Method resolution order:|      SyntaxError|      Exception|      BaseException|      object||  Built-in subclasses:|      IndentationError||  Methods defined here:||  __init__(self, /, *args, **kwargs)|      Initialize self.  See help(type(self)) for accurate signature.||  __str__(self, /)|      Return str(self).
........

【示例9】查看数据类型中某个方法的帮助信息。使用help()函数查看字符类型中 "find" 方法的帮助信息,示例代码如下:

help("str.find")  # 查看字符类型中的"find"方法的帮助信息

输出结果为:

Help on method_descriptor in str:str.find = find(...) unbound builtins.str methodS.find(sub[, start[, end]]) -> intReturn the lowest index in S where substring sub is found,such that sub is contained within S[start:end].  Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure.

【示例10】 查看所有的模块。使用help()函数查看当前python中的所有模块,示例代码如下:

help('modules')  # 查看当前python中所有的模块

输出结果为:

Please wait a moment while I gather a list of all available modules...Crypto              automat             hyperlink           reprlib
DataRecorder        backend_interagg    idlelib             requests
Django5Study        base64              idna                requests_file
DownloadKit         bdb                 imaplib             retrying
DrissionPage        binascii            imghdr              rlcompleter
IPython             bisect              importlib           run
OpenSSL             blinker             importlib_metadata  runpy
PIL                 bs4                 incremental         sched
.........

【示例11】查看Python中提供的帮助主题的列表。使用help()函数查看Python中提供的帮助主题的列表,示例代码如下:

help("topics")  # 查看Python中提供的帮助主题的列表

输出结果为:

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  

【示例12】查看python某一个主题的帮助文档的内容。使用help()函数查看python某一个主题的帮助文档的内容,示例代码如下:

help("UNICODE")  # 查看python某一个主题的帮助文档的内容

输出结果为:

String and Bytes literals
*************************String literals are described by the following lexical definitions:stringliteral   ::= [stringprefix](shortstring | longstring)stringprefix    ::= "r" | "u" | "R" | "U" | "f" | "F"| "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"shortstring     ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'longstring      ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'shortstringitem ::= shortstringchar | stringescapeseqlongstringitem  ::= longstringchar | stringescapeseqshortstringchar ::= <any source character except "\" or newline or the quote>longstringchar  ::= <any source character except "\">stringescapeseq ::= "\" <any source character>bytesliteral   ::= bytesprefix(shortbytes | longbytes)bytesprefix    ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"shortbytes     ::= "'" shortbytesitem* "'" | '"' shortbytesitem* '"'longbytes      ::= "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'shortbytesitem ::= shortbyteschar | bytesescapeseqlongbytesitem  ::= longbyteschar | bytesescapeseqshortbyteschar ::= <any ASCII character except "\" or newline or the quote>longbyteschar  ::= <any ASCII character except "\">bytesescapeseq ::= "\" <any ASCII character>
..........
http://www.xdnf.cn/news/353143.html

相关文章:

  • 【论文阅读27】-TCN–BiLSTM -滑坡预测
  • 从Dockerfile 构建docker镜像——保姆级教程
  • `待办事项css样式
  • electron 结合 react(cra创建的) 创建桌面应用和打包桌面应用
  • 2025年API安全防御全解析:应对DDoS与CC攻击的智能策略
  • rtsp,。。。。
  • 现代框架对SEO的深度影响
  • 【概念解读】开发中遇到的概念阶段
  • RuntimeError: expected scalar type ComplexDouble but found Float
  • 计算机视觉与深度学习 | 视觉+激光雷达+惯惯性SLAM算法汇总(原理,公式,代码)
  • Java中的分布式缓存与Memcached集成实战
  • 电压取样端口静电浪涌防护方案 之6TS Series瞬态抑制器TVS
  • hz2新建Keyword页面
  • 使用 swift 微调 Qwen3-4b 模型
  • 矩阵短剧系统:如何用1个后台管理100+小程序?深度解析多端绑定技术
  • C++--类中this指针的讲解
  • 从数据孤岛到智能工厂:RG3000边缘网关的数字化转型实践
  • Mac QT水平布局和垂直布局
  • 小红书视频无水印下载方法
  • AI技术与园区运营的深度融合:未来生态型园区的建设路径
  • VS Code配置指南:打造高效的QMK开发环境
  • 老旧 LabVIEW 系统升级改造
  • 系统的从零开始学习电子的相关知识,该如何规划?你是工作了18年的电子工程师,请给出你的建议
  • 三维GIS开发cesium智慧地铁教程(6)添加模型
  • 31【干货】Arcgis属性表常用查询表达式实战大全
  • 基于Java和GeoTools的根据矢量BBOx自动生成格网文件实践
  • 基于C++的多线程网络爬虫设计与实现(CURL + 线程池)
  • Java游戏服务器开发流水账(3)游戏数据的缓存简介
  • 第04章—技术突击篇:如何根据求职意向进行快速提升与复盘
  • 数据库索引