1

How does one convert a string to the name of a class in Python? For example, if I have a series of related classes such as MyClass1, MyClass2, MyClassN..., how do I call the class I need if I were in a conditional assuming only the ending number of the string were to change?

Edit: All the classes are already defined. I just need a way to call them depending on the situation. The number will be coming from a GET variable so it would be nice if I can just append that number to a string.

enchance
  • 29,075
  • 35
  • 87
  • 127
  • 4
    There's nothing special about class names. Those are just regular variables. Classes are just objects, like any other. A natural way to map strings to objects is to use a `dict`. Or in your case, maybe a `list` – juanpa.arrivillaga May 14 '20 at 10:08
  • Does this answer your question? [Convert string to Python class object?](https://stackoverflow.com/questions/1176136/convert-string-to-python-class-object) – Diggy. May 14 '20 at 10:10
  • @enchance just use a dict. That is the cleanest solution. If all the classes are in the global scope in the module you need them, then you can just use the `globals()` dict, although that's sort of hacky. Better to just make your own dictionary to keep things clean – juanpa.arrivillaga May 14 '20 at 10:15
  • Also, if they're in a different module, you can use `getattr` to dynamically use a class from an imported module: `getattr(module, 'MyClass{}'.format(num))` – awarrier99 May 14 '20 at 10:17

0 Answers0