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]()