Python:调用名称存储在变量中的构造函数
我有以下变量:Python:调用名称存储在变量中的构造函数,python,constructor,Python,Constructor,我有以下变量: var = 'MyClass' 我想基于变量var创建MyClass的对象。类似于var()。在Python中如何实现这一点?假定类的模块也是一个变量,您可以在需要“MyClass”的类驻留在模块“my.module”中的位置执行以下操作: >>> def hello(): ... print "hello world" ... >>> globals()["hello"]() hello world 此函数将允许您从程序可用的任
var = 'MyClass'
我想基于变量
var
创建MyClass
的对象。类似于var()
。在Python中如何实现这一点?假定类的模块也是一个变量,您可以在需要“MyClass”的类驻留在模块“my.module”中的位置执行以下操作:
>>> def hello():
... print "hello world"
...
>>> globals()["hello"]()
hello world
此函数将允许您从程序可用的任何模块获取任何类的实例,以及构造函数需要的任何参数
def get_instance(mod_str, cls_name, *args, **kwargs):
module = __import__(mod_str, fromlist=[cls_name])
mycls = getattr(module, cls_name)
return mycls(*args, **kwargs)
mod_str = 'my.module'
cls_name = 'MyClass'
class_instance = get_instance(mod_str, cls_name, *args, **kwargs)