栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python反射应用(调用方法和类中方法)——————附带详细实例

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python反射应用(调用方法和类中方法)——————附带详细实例

文章目录 0 结果1 调用方法2 调用类中的方法3 调用测试的代码

0 结果

文件目录

调用方法

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)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/268225.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号