0

I have a python module that calls multiple other classes within the same module.

class Main(object):
   def foo(self):
      return 'bar'
   def getClass(self, className, *args):
      return eval(className + "(%s)" % ",".join(args))
class A(object):
   def __init__(self, b):
      self._b = b
class B(object):
   def __init__(self, c):
      self._c = c

What I would like to do is this. In the class Main, I want to generate a class Object by only knowing the class name, and passing in the variables needed to create that class.

I now I can do conditional if/else, but I was wondering if it was possible. I figured I could use eval() as well, but i heard that can be evil.

Suggestions? Comments? I have a class that references multiple sublcasses, and instead of creating a class for each type, I figured this would be easier to do.

Thank you

code base 5000
  • 3,812
  • 13
  • 44
  • 73
  • This is a dupe of several questions here. For example: http://stackoverflow.com/questions/1176136/convert-string-to-python-class-object. While the accepted answer uses eval(), several other options are provided that don't. – dano Apr 09 '14 at 14:28
  • `eval` is probably not the right way to go. If you want to create instances of a subclass of `cls` in some `@classmethod`, you can look in `cls.__subclasses__()`, a list of the sub-classes – jonrsharpe Apr 09 '14 at 14:31

0 Answers0