Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to call specific classes based on a variable?

I want a program to call a specific class based on a parameter/variable value. However, I don’t want to use any clunky if-statements. My first thought was to use the globals() function, but I couldn’t get it to work. Here’s an example:

class SomeClass:
    def __init__():
        print("Hello, world!")

class OtherClass:
    def runClass(className):
        # Call class based on variable className

The reason I want to do this is because there is a wide variety of classes may need to be called, and so just piling up if-statements in my code won’t do it. Any help would be greatly appreciated. Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here’s how you can call a class via globals

class SomeClass:
    def __init__(self):
        print("Hello, world!")

    def __call__(self):
        return "SomeClass called"

class OtherClass:
    def runClass(self, className):
        globals()[className]()()
        
o = OtherClass()
result = o.runClass("SomeClass")
print(result)

Notice, I am instantiating and then calling it via the __call__ special method, which is the closest match to your description I could think of.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading