python 作为变量名导入
python import as a variable name
我想使用带有变量名的导入。例如我想做这样的事情
from var import my_class
我经历了 pythons documentation,但似乎有点混乱。我还看到了一些关于堆栈溢出的其他帖子,给出了类似这样的例子
import importlib
my_module = importlib.import_module("var, my_class)
第二个例子在一定程度上确实有效。我在这里看到的唯一问题是导入了 var,但我没有在 python 的命名空间中看到 my_class 的属性。我如何将其等同于
的原始示例
from var import my_class
注意:正如@DYZ 在评论中指出的那样,不推荐使用这种解决方法来支持 importlib。为了另一个可行的解决方案而将其留在这里,但 Python docs 建议 "Direct use of import() is also discouraged in favor of 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__
方法来获取函数,然后像往常一样用()
调用它。下面标记为 "See note" 的行不是必需的,我只是包含它以表明 __getattribute__
方法正在返回一个函数。
>>> 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'
更多文档可用于 Python 3 here or Python2 here。
下面是importlib
的使用方法(不需要第二个参数):
var = importlib.import_module("var")
# Now, you can use the content of the module:
var.my_class()
from var import my_class
没有直接可编程的等价物。
我想使用带有变量名的导入。例如我想做这样的事情
from var import my_class
我经历了 pythons documentation,但似乎有点混乱。我还看到了一些关于堆栈溢出的其他帖子,给出了类似这样的例子
import importlib
my_module = importlib.import_module("var, my_class)
第二个例子在一定程度上确实有效。我在这里看到的唯一问题是导入了 var,但我没有在 python 的命名空间中看到 my_class 的属性。我如何将其等同于
的原始示例from var import my_class
注意:正如@DYZ 在评论中指出的那样,不推荐使用这种解决方法来支持 importlib。为了另一个可行的解决方案而将其留在这里,但 Python docs 建议 "Direct use of import() is also discouraged in favor of 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__
方法来获取函数,然后像往常一样用()
调用它。下面标记为 "See note" 的行不是必需的,我只是包含它以表明 __getattribute__
方法正在返回一个函数。
>>> 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'
更多文档可用于 Python 3 here or Python2 here。
下面是importlib
的使用方法(不需要第二个参数):
var = importlib.import_module("var")
# Now, you can use the content of the module:
var.my_class()
from var import my_class
没有直接可编程的等价物。