Python: calling a constructor whose name is stored in a variable

I have the following variable:

var = 'MyClass' 

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

0
source share
2 answers
 >>> def hello(): ... print "hello world" ... >>> globals()["hello"]() hello world 
0
source

Assuming you have a class module as a variable, you can do the following: the class in which you want "MyClass" is in the "my.module" 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 allow you to get an instance of any class with any arguments needed by the constructor from any module available for your program.

0
source

All Articles