Python __import__() 函式


我們在編寫 python 程式時需要其他各種模組,以充分利用當前程式中的函式、類等。我們可以使用 import 函式在執行時匯入這些模組。雖然你也可以在程式碼的開頭匯入命名模組,但你可能只需要暫時使用該模組且僅涉及幾行程式碼,或者你希望從該模組中複製一個物件並對其進行修改和使用。

語法

__import__() 函式的語法如下 −

__import__(name, globals=None, locals=None, fromlist=(), level=0)
Where
name - the name of the module you want to import
globals and locals - determines how to interpret name
fromlist - objects or submodules that should be imported by name
level - specifies whether to use absolute or relative imports

在下面的示例中,我們匯入 DateTime 模組並建立自定義物件,其中包含程式所需的值。

示例

 演示

dttime = __import__('datetime', globals(), locals(), [], 0)
print(dttime.datetime.now())
# Make a copy of dttime
x = dttime.datetime.now()
# Get your custom results
print(x.strftime("%d-%B"))

輸出

執行以上程式碼將得到以下結果 −

2021-01-12 07:38:54.903330
12-January

不推薦使用 __import__,你可以出於更高的效率在程式碼的開頭匯入整個模組。

更新於: 2021 年 1 月 25 日

368 瀏覽

開啟你的 職業生涯

完成課程,取得認證

行動起來
廣告