Skip to content Skip to sidebar Skip to footer

Python: Call A Constructor Whose Name Is Stored In A Variable

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?

Solution 1:

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

Solution 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":

defget_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.

Post a Comment for "Python: Call A Constructor Whose Name Is Stored In A Variable"