2名名名名名名名名名名名名名名名名名名名 2022-12-13 12:07 采纳率: 26.3%
浏览 13

关于#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

  • 写回答

1条回答 默认 最新

  • BsonJ 2022-12-13 12:18
    关注

    What is your question

    评论

报告相同问题?

问题事件

  • 创建了问题 12月13日