特定の文字列からクラスを動的にロードしたい。ただし、クラスがどのファイルに含まれるかわからないため、すべてのファイルを検索する必要があります。私はこれを試しましたがAttributeError: 'module' object has no attribute 'MyClass'
、そのモジュール (現在の反復) がそのクラスを持っていることを 100% 確信しているにもかかわらず、取得します:
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'
かなり近づいているようです。私が望むのは、検索を 1 つのフォルダーだけに限定するのではなく、おそらく複数のフォルダーに限定することです。コードの何が問題になっていますか?
編集:わかりました今、私はこのようなことを試みていますが、それでも同じエラーが発生します:
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'