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

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

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

可能会执行以下 *** 作:

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)


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5664440.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存