david3000
david3000

Reputation: 11

How to get an existing class based on class name?

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).

Upvotes: 0

Views: 188

Answers (2)

martineau
martineau

Reputation: 123473

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'>

Upvotes: 1

Some Intern Coder
Some Intern Coder

Reputation: 16

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.

Upvotes: 0

Related Questions