I have a class:
class Test():
pass
I know the class name is "Test"
. How can I get class Test
? A class is an object of class. I would like to get the class object based on its name, the text "Test"
.
In my project I have many classes defined. I would like to instantiate a class based on its name (without using an if
statement).
CodePudding user response:
If the class is defined in the global namespace, you can do it this way:
class Test:
pass
test_class = globals()["Test"]
print(test_class) # -> <class '__main__.Test'>
CodePudding user response:
I don't suggest following such a convention, as this is very bad practice. A class is not an object of class, it's just a class that has been defined. Any objects you define using that class will be an object of that class and have its own instance. Please don't use the same name for different classes, this is almost never maintainable and you should never do it this way.