0

I want to take advantage of polymorphism where the class that should be used for a certain action is defined in the database. Basically I want something that can work like this:

class Example:
    @staticmethod
    def do_something():
        # Does something

s = "Example"
# Do magic here that makes s reference the class instead of just being a string
s.do_something()

Obviously, there probably needs to be some code to check it actually is a class that's defined and all that.

Tom Ribbens
  • 210
  • 1
  • 10
  • [Check This related post here](https://stackoverflow.com/questions/1176136/convert-string-to-python-class-object). Hope this helps. – Israt Sep 25 '22 at 13:56

1 Answers1

0

You can check if the class name exists in globals():

class Example:
    @staticmethod
    def do_something():
        print("Hello from ExampleClass")


li = ["Example", "WrongExample"]

for cls in li:
    if cls in globals():
        print(f"Calling class {cls}:")
        globals()[cls]().do_something()
    else:
        print(f"Class {cls} does not exists.")
        
# Calling class Example:
# Hello from ExampleClass
# Class WrongExample does not exists.
JarroVGIT
  • 4,291
  • 1
  • 17
  • 29