关于#python#的问题,请各位专家解答!

0

One approach you could try is using the built-in getattr() function, which can be used to get the attribute of an object by its name (as a string). In your case, you could use it to get a reference to the class object based on the value of className, and then you can create an instance of the class and call its methods. Here's an example:

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

class OtherClass:
    def runClass(self, className):
        # Get the class object based on the value of className
        cls = getattr(sys.modules[__name__], className)

        # Create an instance of the class and call its __init__ method
        instance = cls()
        instance.__init__()

# Create an instance of OtherClass and call the runClass method
other = OtherClass()
other.runClass("SomeClass")

  • 1
  • 2
  • 3
  • 4
  1. img

What is your question