您可能会执行以下 *** 作:
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)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)