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?
解决方案
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.