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

发布于:2025-05-10 ⋅ 阅读:(15) ⋅ 点赞:(0)

一、语法参考

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

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 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中的所有模块,示例代码如下:

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 | 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>
..........

网站公告

今日签到

点亮在社区的每一天
去签到