0

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?

0

2 Answers 2

0
>>> def hello():
...     print "hello world"
... 
>>> globals()["hello"]()
hello world
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.