python学习笔记15:通过字符串导入模块

1 使用importlib(官方推荐方法)

import importlib

s_path = ‘auth.my_auth.CAuth’
s_path_name, s_class_name = s_path.rsplit(‘.’, 1)
o_module = importlib.import_module(s_path_name)

CClass = getattr(o_module, s_class_name) # 获取对应的class
o_obj_0 = CClass() # 实例化
o_obj_1 = getattr(o_module, s_class_name)() #  获取class’后直接实例化

2 使用__import__函数

s_module_name = ‘os’
__import__(s_module_name)

3 使用exec

s_module_name = ‘os’
exec(f’import {s_module_name}’)
原文地址:https://www.cnblogs.com/gaiqingfeng/p/13231521.html