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

目录

一、语法参考

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

参数说明:

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

二、示例

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

python 复制代码
help(input)  # 查看input()函数的信息

输出结果为:

python 复制代码
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 a
    trailing 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中所有的保留字,示例代码如下:

python 复制代码
help('keywords')  # 查看所有的关键字

输出结果为:

python 复制代码
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()函数启动帮助系统,查看对象的帮助信息,示例代码如下:

python 复制代码
help()  # 调用help()函数,不传入参数

输出结果如下图所示:

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

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

python 复制代码
help('os')  # 查看os模块的帮助信息

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

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

输出结果为:

python 复制代码
Help on function abspath in os.path:

os.path.abspath = abspath(path)
    Return the absolute version of a path.

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

python 复制代码
help('str')  # 查看str数据类型的帮助

输出结果为:

python 复制代码
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" 的帮助信息,示例代码如下:

python 复制代码
help("if")  # 查看if保留字的帮助信息

输出结果为:

python 复制代码
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" 的帮助信息,示例代码如下:

python 复制代码
help("SyntaxError")  # 查看语法错误"SyntaxError"的帮助信息

输出结果为:

python 复制代码
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" 方法的帮助信息,示例代码如下:

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

输出结果为:

python 复制代码
Help on method_descriptor in str:

str.find = find(...) unbound builtins.str method
    S.find(sub[, start[, end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.

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

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

输出结果为:

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中提供的帮助主题的列表,示例代码如下:

python 复制代码
help("topics")  # 查看Python中提供的帮助主题的列表

输出结果为:

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某一个主题的帮助文档的内容,示例代码如下:

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

输出结果为:

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 | stringescapeseq
   longstringitem  ::= longstringchar | stringescapeseq
   shortstringchar ::= <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 | bytesescapeseq
   longbytesitem  ::= longbyteschar | bytesescapeseq
   shortbyteschar ::= <any ASCII character except "\" or newline or the quote>
   longbyteschar  ::= <any ASCII character except "\">
   bytesescapeseq ::= "\" <any ASCII character>
..........
相关推荐
二进制漫游记1 分钟前
FastAPI项目集成 Qdrant向量数据库+阿里云Embedding完整实战(工具封装+业务调用)
数据库·python·阿里云·embedding
-今昭-44 分钟前
《V2V 迁移实战:将 VMware 虚拟机转为 OpenStack 可用 Glance qcow2 镜像》
开发语言·python
2601_962381581 小时前
【转】Python渗透测试工具:sqlmap
python·渗透测试·sql注入·sqlmap·数据库安全
用户3721574261352 小时前
如何使用 Python 从 Word 文档中提取图片
python
白山编程大哥3 小时前
Java 集合算法:从排序、查找到底层原理的实战指南
java·python·算法
昭昭日月明4 小时前
RAGFlow 入门,不用从零造轮子
python·ai编程
莓有烦恼吖5 小时前
Vibe Coding 的一些思考
python
小白学大数据5 小时前
超简单:用 Python 让 Excel 飞起来:用 openpyxl 把重复报表整理交给脚本
开发语言·数据库·python·excel
爱丶不疚5 小时前
写给前端工程师的现代 Python 工程化最佳实践:从 pnpm 到 uv,从 CommonJS 到 src-layout
javascript·python·typescript
2601_962297256 小时前
C# vs Java vs Python:YOLO工业部署性能对比实战
java·python·c·工业视觉·性能对比