0

I have the name of the class in string like this:

className = "MyClassName"

I have already imported the MyClassName in my model.

is there a way to use this:

Object = MyClassName()

What I have thought of

making if else statment like this:

if className == "MyClassName":
    Object = MyClassName()
elif className == "MyClass2":
    Object = MyClass2()

I hope there is a better way

2
  • You could use object = globals()[className]() Commented Feb 21, 2014 at 10:45
  • The question is.. Why do you want to do this? Commented Feb 21, 2014 at 10:49

2 Answers 2

3

You get the current module using sys.modules[__name__] and then get the class with getattr, like this

var = "MyClassName"
import sys
mod = sys.modules[__name__]
getattr(mod, var)()

Or as @lanzz suggested in the comments,

globals()[var]()

Suggestion by @Ashwini Chaudhary in the chat room,

classes = {"MyClassName": MyClassName, "MyClass2": MyClass2}

You can then use the classes dictionary to get the corresponding classes. I would prefer this way, particularly if the input comes from the user.

Sign up to request clarification or add additional context in comments.

1 Comment

which is the better way, yours or lanzz's?
0

you can use eval function.

var = "MyClassName"
ob = eval(var + "()")

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.