1

特定の文字列からクラスを動的にロードしたい。ただし、クラスがどのファイルに含まれるかわからないため、すべてのファイルを検索する必要があります。私はこれを試しましたが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'
4

3 に答える 3

2

のドキュメントからimp.new_module、返されたモジュールはです。あなたのクラスが決して含まれないことを意味します。

おそらく、ターゲットディレクトリを追加して、それらのモジュールを動的にインポートするためにsys.path使用してから、クラスを確認することをお望みですか?__import__


次のコードは私にとってはうまくいきます:

modules = ['foo','bar']
for mod in modules:
    try:
        x = reload(__import__(mod))
    except ImportError:
        print "bargh! import error!"
        continue
    try:
        cls = getattr(x,'qux')
    except AttributeError:
        continue

a = cls()
print a.__class__.__name__

foo.pybar.pyは同じディレクトリにあります。

#foo.py
class foo(object):
    pass

と:

#bar.py
class qux(object):
    pass
于 2012-11-14T16:20:59.850 に答える
1

ドキュメント new_moduleの返品と空のモジュールによると:

imp.new_module(name) name という名前の新しい空のモジュールオブジェクトを
返します。このオブジェクトは sys.modules には挿入されません。

代わりにimp.load_sourceを見たいと思うかもしれません。これは簡単な例です:

class Test:
    pass

In [19]: m = imp.load_source("test", "./test.py")
In [20]: getattr(m, "Test")
Out[20]: <class test.Test at 0x1fe6120>
于 2012-11-14T16:20:57.580 に答える
0

impドキュメントの例に従ってください:

hello.py という名前の同じディレクトリにあるファイル:

def myFunction():
        return "Hello World!"

hello を動的にインポートします (finally 以外は try なし):

fp, pathname, description = imp.find_module("hello")
hello = imp.load_module("hello", fp, pathname, description)
hello.myFunction() # returns 'Hello World!'
于 2015-02-23T16:28:51.063 に答える