注の私の元の例にこれを等しくなります:@DYZはコメントで指摘するように、これを解決するためのこの方法は、のimportlibの賛成で推奨されていません。別の解決策のためにここに残してください。Python docsアドバイス「直接使用のインポート()は、importlib.import_module()のために推奨されません。
名前で変数が定義されているモジュールをインポートすることを意味しますか?その場合は__import__
メソッドを使用できます。たとえば、次のように
>>> import os
>>> os.getcwd()
'/Users/christophershroba'
>>>
>>> name_to_import = "os"
>>> variable_module = __import__(name_to_import)
>>> variable_module.getcwd()
'/Users/christophershroba'
あなたも、あなたが機能を取得するためにモジュールに__getattribute__
メソッドを使用して、通常通り()
でそれを呼び出すことができ、その変数モジュールの変数メソッドを呼び出したい場合は
。 「注記」と記されている行は必要ありません。
__getattribute__
メソッドが関数を返すことを示すためにその行を含めます。
Python 3 hereまたは
Python2 hereために利用可能な
>>> name_to_import = "os"
>>> method_to_call = "getcwd"
>>> variable_module = __import__(name_to_import)
>>> variable_module.__getattribute__(method_to_call) # See note
<built-in function getcwd>
>>> variable_module.__getattribute__(method_to_call)()
'/Users/christophershroba'
その他のドキュメント。ここで
これは私が間違って使用していた。ありがとう。 – Matt
'my_class = importlib.import_module(" var ").__ getattribute __(" my_class ")'は、 'from var import my_class'の直接プログラマブルな同等物ですか? –
@ChristopherShroba私はあなたができると思います。 – DyZ