Python:调用其名称存储在变量中的构造函数

时间:2013-06-22 12:59:49

标签: python constructor

我有以下变量:

var = 'MyClass'

我想基于变量MyClass创建var的对象。像var()这样的东西。我怎么能用Python做到这一点?

2 个答案:

答案 0 :(得分:0)

>>> def hello():
...     print "hello world"
... 
>>> globals()["hello"]()
hello world

答案 1 :(得分:0)

假设您将类'模块作为变量,您可以执行以下操作,其中您想要的类“MyClass”位于模块“my.module”中:

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)

此函数将允许您从程序可用的任何模块中获取任何类的实例,其中包含构造函数所需的任何参数。

相关问题