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.

4
  • 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 Commented May 14, 2020 at 10:08
  • Does this answer your question? Convert string to Python class object? Commented May 14, 2020 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 Commented May 14, 2020 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)) Commented May 14, 2020 at 10:17

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.