Zuletzt aktiv 9 months ago

importlib 允許在執行時動態載入模組,適用於 外部插件管理、模組熱加載、延遲載入以提升效能 等場景。

timmy hat die Gist bearbeitet 9 months ago. Zu Änderung gehen

3 files changed, 25 insertions

dynamic_function_call.py(Datei erstellt)

@@ -0,0 +1,10 @@
1 + import importlib
2 +
3 + module_name = "math"
4 + function_name = "factorial"
5 +
6 + # 載入模組並取得函式
7 + module = importlib.import_module(module_name)
8 + func = getattr(module, function_name)
9 +
10 + print(func(5)) # 120

dynamic_module_loading.py(Datei erstellt)

@@ -0,0 +1,10 @@
1 + import importlib
2 +
3 + # 動態載入內建模組
4 + math_module = importlib.import_module("math")
5 + print(math_module.sqrt(16)) # 4.0
6 +
7 + # 動態載入自訂模組
8 + module_name = "my_module" # 假設有 my_module.py
9 + custom_module = importlib.import_module(module_name)
10 + print(custom_module.hello()) # 假設 my_module 有 hello() 函式

reload_module.py(Datei erstellt)

@@ -0,0 +1,5 @@
1 + import importlib
2 + import my_module # 假設 my_module.py 已存在
3 +
4 + # 重新載入模組(適用於修改後立即生效)
5 + importlib.reload(my_module)
Neuer Älter