反射应用实例:importlib模块
反射应用实例:importlib模块
#示例1
import importlib
redis = importlib.import_module("测试")
getattr(redis,"func")()
redis.func() #与上一行等价
#示例2
#给定字符串并自动执行某个函数
import importlib
path = "utils.redis.func" #给定一个函数路径
module_path,func_path = path.rsplit(".",maxsplit = 1)
module_object = importlib.import_module(module_path)
getattr(module_object,func_path)()
#示例3
#调用跨文件的类
import importlib
list = [
"day12.redis.Foo",
"day12.mongo.Mongo",
"day12.mins.Fgg"
]
for path in list:
module_path,class_name = path.rsplit(".",maxsplit=1)
# print(module_path,class_name)
module_object = importlib.import_module(module_path)
redi = getattr(module_object,class_name)
cls = redi()
cls.func()
记录学习的点点滴滴