栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

动态导入模块,然后从所述模块实例化具有特定基类的对象

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

动态导入模块,然后从所述模块实例化具有特定基类的对象

您可能会执行以下操作:

for c in candidates:    modname = os.path.splitext(c)[0]    try:        module=__import__(modname)   #<-- You can get the module this way    except (importError,NotImplementedError):        continue    for cls in dir(module):          #<-- Loop over all objects in the module's namespace        cls=getattr(module,cls)        if (inspect.isclass(cls)     # Make sure it is a class  and inspect.getmodule(cls)==module  # Make sure it was defined in module, not just imported and issubclass(cls,base)):          # Make sure it is a subclass of base # print('found in {f}: {c}'.format(f=module.__name__,c=cls)) classList.append(cls)

为了测试以上内容,我不得不对您的代码进行一些修改;以下是完整的脚本。

import sysimport inspectimport osclass Pluginbase(object): passdef search(base):    for root, dirs, files in os.walk('.'):        candidates = [fname for fname in files if fname.endswith('.py') and not fname.startswith('__')]        classList=[]        if candidates: for c in candidates:     modname = os.path.splitext(c)[0]     try:         module=__import__(modname)     except (importError,NotImplementedError):         continue     for cls in dir(module):         cls=getattr(module,cls)         if (inspect.isclass(cls)  and inspect.getmodule(cls)==module  and issubclass(cls,base)):  # print('found in {f}: {c}'.format(f=module.__name__,c=cls))  classList.append(cls)        print(classList)search(Pluginbase)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/662484.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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