Python: Call a constructor whose name is stored in a variable [duplicate]

末鹿安然 提交于 2019-12-11 16:46:26

问题


I have the following variable:

var = 'MyClass'

I would like to create an object of MyClass based on the variable var. Something like var(). How can I do this in Python?


回答1:


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



回答2:


Presuming you have the class' module as a variable as well, you can do the following, where the class you want "MyClass" resides in module "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)

This function will let you get an instance of any class, with whatever arguments the constructor needs, from any module available to your program.



来源:https://stackoverflow.com/questions/17251008/python-call-a-constructor-whose-name-is-stored-in-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!