Python __import__() 函式



Python __import__() 函式 是一個 內建函式,用於在執行時匯入模組。需要注意的是,通常不建議使用此函式,因為它可能會改變 import 語句的語義。

在我們的 Python 程式中,我們需要來自其他 模組 的各種 函式 和類。雖然我們也可以在程式碼開頭匯入命名模組,但有時我們可能只需要在幾行程式碼中臨時使用該模組。在這種情況下,我們使用 __import__() 函式。

語法

以下是 Python __import__() 函式的語法:

__import__(name, globals, locals, fromlist, level)

引數

Python __import__() 函式接受以下引數:

  • name - 它表示我們希望在程式中匯入的模組的名稱。

  • globals - 它指定如何解釋指定的模組。

  • locals - 它也指定如何解釋匯入的模組。

  • fromlist - 此引數指定我們希望作為列表匯入的物件或子模組。

  • level - 等級 0 表示絕對,正數表示相對等級。

返回值

Python __import__() 函式返回我們指定的物件或模組。

__import__() 函式示例

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

示例:__import__() 函式的使用

以下示例展示了 Python __import__() 函式的基本用法。在這裡,我們正在將名為“math”的模組匯入到我們的程式中。

#importing the module
importingModule = __import__("math")
# using sqrt method from the module
print(importingModule.sqrt(49))

當我們執行上述程式時,它會產生以下結果:

7.0

示例:使用 __import__() 在執行時呼叫模組的特定方法

我們還可以從給定模組中選擇一個特定方法匯入到我們的程式中。在下面的程式碼中,我們僅從 Math 模組 匯入 sqrt() 方法

#importing only sqrt method from Math module
importingSqrt = getattr(__import__("math"), "sqrt")
print("The square root of given number:")
print(importingSqrt(121))

以下是上述程式碼的輸出:

The square root of given number:
11.0

示例:使用 __import__() 函式為模組指定別名進行匯入

以下程式碼演示瞭如何透過為其指定別名來匯入 numpy 模組

#importing only numpy module
np = __import__('numpy', globals(), locals(), [], 0)
print("The newly created array:")
print(np.array([22, 24, 26, 28, 30, 32]))

以上程式碼的輸出如下:

The newly created array:
[22 24 26 28 30 32]
python_built_in_functions.htm
廣告