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

标签 python python-3.x class methods

<分区>

备注: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的现有方法。

最佳答案

getattr怎么样? ?

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

myclass = SomeClass()
method = input("What do you want to execute? ")
getattr(myclass, method)()

结果:

C:\Users\Kevin\Desktop>py -3 test.py
What do you want to execute? bark
woof

关于python - 在构建时调用未指定的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44204592/

相关文章:

python - django 翻译模板 {% trans "something"%}

python - 在多核上运行 Python

java - 有条件地更改 Java 对象类

python - 在 Python 中缓存已编译的正则表达式对象?

python - 如何修复此 Django 错误 "Exception Type: OperationalError Exception Value: no such table?"

python - 如何使用列表理解从列表列表中的 "diagonal"范围创建列表?

python - 加载 Python lib '/tmp/_MEItueAuk/libpython3.7m.so.1.0' : dlopen:/lib/x86_64-linux-gnu/libc. so.6 时出错:未找到版本 `GLIBC_2.28'

c++ - 将类映射到字符串

c# - 数据库工厂类设计

python - Testbed 中的数据存储 key 不正确