-2

Give some class definitiona in python, e.g.

class A(object):
    def __init__(self):
        self.x = 5

class B(object):
    def __init(self):
        self.x = 42

I want to instantiate one of these classes given its name as string. So for example, if classname is A, then I want to do something like

myinstance = SOMETHING(classname)

which should correspond to

myinstance = A()

Is there a way to do this without the use of eval eval or maps? If not, I would do the following:

map = {'A': A, 'B': B}
myinstance = map[classname]()
martineau
  • 119,623
  • 25
  • 170
  • 301
Alex
  • 41,580
  • 88
  • 260
  • 469

1 Answers1

0

Considering that the Python naming scheme is based on maps, you will be using maps of one sort or another even if you use eval.

Building your own map is the most appropriate, but you can also use globals() or retrieve it from a module if your classes are stored somewhere else:

import util_module
getattr(util_module, 'A') ()
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237