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

Nar*_*san 1 python methods class python-3.x

注意:类似的问题已经存在,尽管是针对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() 
Run Code Online (Sandbox Code Playgroud)

我不会在建造时知道SomeClass将要调用什么方法.如果你有200种方法而且只有2种方法可供选择,那么if-then-else也不是很整洁.

如何在python中最有效地完成?

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

Kev*_*vin 5

怎么样getattr

class SomeClass:
    def bark(self):
        print("woof")

myclass = SomeClass()
method = input("What do you want to execute? ")
getattr(myclass, method)()
Run Code Online (Sandbox Code Playgroud)

结果:

C:\Users\Kevin\Desktop>py -3 test.py
What do you want to execute? bark
woof
Run Code Online (Sandbox Code Playgroud)