Python help() 函式



Python 的 help() 函式 是一個內建的幫助系統,可以用於任何物件、類、函式或模組,以獲取有關它的更多資訊。

如果向此函式傳遞引數,則會生成有關該引數的幫助頁面。在沒有傳遞引數的情況下,會在直譯器控制檯上顯示互動式幫助系統。此函式是 內建函式 之一,您無需匯入任何內建模組即可使用此方法。

語法

python help() 函式的語法如下所示:

help(object)

引數

python help() 函式接受一個引數:

  • object - 此引數指定需要幫助的物件。

返回值

python help() 函式返回與傳遞的物件相關的資訊。

help() 函式示例

練習以下示例以瞭解如何在 Python 中使用 help() 函式。

示例:help() 函式的使用

以下示例顯示了 Python help() 函式的基本用法。在這裡,我們將內建函式 "print()" 作為引數傳遞給 help() 函式,它將顯示該函式的簡要說明。

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.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

示例:使用 help() 函式獲取模組的詳細資訊

如果我們想顯示 Python 內建模組 的詳細資訊,我們只需匯入它並將該模組作為引數值傳遞給 help() 函式。

import math
help(math)

以下是執行上述程式獲得的輸出:

Help on built-in module math:
NAME
    math
DESCRIPTION
    This module provides access to the mathematical functions
    defined by the C standard.

示例:使用 help() 函式獲取類的詳細資訊

如果我們將類名作為引數傳遞給 help() 函式,則該函式將返回類的描述。它將顯示傳遞類的 屬性 和其他方法。

class NewClass:
   def firstExample(self):
      """
      This is an example of NewClass.
      """
      pass

help(NewClass)

以下是執行上述程式獲得的輸出:

Help on class NewClass in module __main__:

class NewClass(builtins.object)
 |  Methods defined here:
 |  
 |  firstExample(self)
 |      This is an example of NewClass.

示例:使用 help() 函式獲取本地方法的詳細資訊

藉助 help() 函式,我們還可以顯示本地方法的描述,如下例所示。

class NewClass:
   def firstExample(self):
      """
      This is an example of NewClass.
      """
      pass

newObj = NewClass()
help(newObj.firstExample)

執行上述程式後,將顯示以下輸出:

Help on method firstExample in module __main__:

firstExample() method of __main__.NewClass instance
    This is an example of NewClass.
python_built_in_functions.htm
廣告