我想动态加载给定字符串中的类。但是,我不知道这个类将会在哪个文件中,所以我将不得不搜索所有文件。我试过这个,但我得到AttributeError: 'module' object has no attribute 'MyClass'
即使我100%肯定该模块(当前迭代)具有类:在Python中动态导入类
target = 'MyClass'
module_names = [mf[0:-3] for mf in os.listdir('application/models') if mf.endswith(".py")]
modules = [imp.new_module(x) for x in module_names]
for module in modules:
try:
target_class = getattr(module, target)
except ImportError, AttributeError:
continue
if target_class:
print 'found class'
看来我得到非常接近。我想要的不是将搜索限制在一个文件夹中,而是可能是多个文件夹。我的代码有什么问题?
编辑:好,现在我想这样的事情,但仍然得到了同样的错误:
for m in module_names:
try:
x = reload(__import__(m))
target_class = getattr(x, target)
except ImportError, AttributeError:
continue
else:
break
if target_class:
print 'found class'
你可能需要一个'break'一旦你找到'target_class' – mgilson
检查更新 – iabdalkader