python动态导入自定义方法
官方推荐方式: imprrtlib
demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# custom_module.py
def custom_function():
print("This is a custom function.")
class CustomClass:
def custom_method(self):
print("This is a custom method in CustomClass.")
#============================================================#
scripts_dir = os.path.join(os.path.dirname(__file__), 'modules')
path.append(scripts_dir)
# main.py
import importlib
# 不同目录,还是要将scripts 目录到 sys.path, 绝对路径
scripts_dir = os.path.join(os.path.dirname(__file__), 'modules')
path.append(scripts_dir)
class MainClass:
def __init__(self):
print("MainClass initialized.")
def load_custom_function(self):
custom_module = importlib.import_module('custom_module')
custom_function = getattr(custom_module, 'custom_function')
custom_function()
def load_custom_class_method(self):
custom_module = importlib.import_module('custom_module')
CustomClass = getattr(custom_module, 'CustomClass')
instance = CustomClass()
instance.custom_method()
if __name__ == "__main__":
main_instance = MainClass()
# 在运行时加载并调用自定义函数
main_instance.load_custom_function()
# 在运行时加载并调用自定义类的方法
main_instance.load_custom_class_method()
说明
1
2
3
4
5
importlib.import_module:该函数用于动态导入模块。您可以传递模块的名称(字符串)来导入该模块。
getattr:该函数用于从模块中获取指定的属性(方法或类)。您可以传递模块和属性的名称(字符串)来获取该属性。
方法调用:一旦您动态导入了模块和属性,就可以像普通方法或类一样调用它们。
优点
1
2
延迟加载:动态导入允许您延迟加载模块,只有在需要时才导入。这可以减少启动时间和内存消耗。
灵活性:您可以根据条件动态选择要导入的模块或类,使您的代码更具灵活性。
自定义的方式
1
2
3
4
5
6
7
8
9
# 1. 添加 scripts 目录到 sys.path
scripts_dir = os.path.join(os.path.dirname(__file__), 'modules')
path.append(scripts_dir)
# 2. 导入对应的 自定义文件
from get_vmSphere_inst import *
from k8s_pod_info import *
本文由作者按照
CC BY 4.0
进行授权