Skip to main content
 首页 » 编程设计

python之在构建时调用未指定的方法

2025年05月04日24开发

<分区>

备注:A similar question已经存在,尽管是针对 C# 的。

假设我的代码如下所示:

class SomeClass: 
 
    def __init__(self): 
         pass 
 
    def do(self): 
        print("a") 
 
class SomeOtherClass: 
 
    def __init__(self): 
         pass 
 
    def do(self): 
        print("b") 
 
class B: 
 
    def __init__(self): 
         self.SomeClass = SomeClass()   
         self.SomeOtherClass = SomeOtherClass() 
 
def __main__(): 
    myclass = B() 
    desired_class = str(input("The method of which class do you want to execute? ")) 
    myclass.desired_class.do()  

我不知道在构建时将调用 SomeClass 的什么方法。如果您有 200 种方法而没有 2 种可供选择,那么 If-then-else 也不是很整洁。

如何在 python 中最有效地完成这项工作?

注意:方法将始终是SomeClass的现有方法。