文件目录
调用方法
executeModel2( model.testModel2 , [1, 2])
调用类中的方法
executeModel( model.add , [1, 2])
优点
自动引包 类名和方法名通过参数传入来调用 1 调用方法方法
def executeModel2(config, input):
model, func config.strip().split( . )
module __import__(f lib.{model} , fromlist True)
if hasattr(module, func):
func getattr(module, func)
func(input)
else:
print( 模型不存在 )
调用测试
executeModel2( model.testModel2 , [1, 2])
解释
__import__(f lib.{model} , fromlist True)相当于import lib.model hasattr 判断对象是否存在某个方法 getattr 返回对象指定属性的值 2 调用类中的方法方法
def executeModel(config, input):
model, func config.strip().split( . )
model_class_name str.upper(model[0]) model[1:len(model)]
module __import__(f lib.{model} , fromlist [model_class_name])
import inspect
for obj_name, obj in inspect.getmembers(module):
if inspect.isclass(obj): # 实例化对象
print(obj_name, obj)
if obj_name model_class_name Input :
model_input obj(*input)
elif obj_name model_class_name:
model_class obj( 测试反射模型 )
else:
pass
# 调用对象中方法
model_method getattr(model_class, func)
model_method(model_input)
调用测试
executeModel( model.add , [1, 2])3 调用测试的代码
model.py
class ModelInput:
def __init__(self, num1, num2):
self._num1 num1
self._num2 num2
property
def num1(self):
return self._num1
property
def num2(self):
return self._num2
class Model:
def __init__(self, model_info):
self._model_info model_info
def add(self, input):
res input.num1 input.num2
print(f {self._model_info}:{res} )
def testModel2(params list()):
print(params)



