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

Bach
  • 6,145
  • 7
  • 36
  • 61
Marco Dinatsoli
  • 10,322
  • 37
  • 139
  • 253

2 Answers2

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.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

you can use eval function.

var = "MyClassName"
ob = eval(var + "()")
BlackMamba
  • 10,054
  • 7
  • 44
  • 67