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.
blazetopher
source share