如何将字符串转换为属性?

Kin*_*III 3 python python-3.x

我正在尝试制作一个非常简单的基于命令的python脚本,并从终端的输入获取命令,但是它没有检测到变量的值...我不善于解释,所以这是我的代码:

a = 0
b = 0

class commands:
    def add():
        a = int(input("first number "))
        b = int(input("second number "))
        print(a + b)

commander = commands
cmd = input("what command ")
commander.cmd()
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它给我一个错误,提示Exception has occurred: AttributeError type object 'commands' has no attribute 'cmd' 我对Python还是比较陌生的,如果真的很明显,请对不起。谢谢您,我们将为您提供帮助。

Dam*_*ero 5

您只需要做:

getattr(commander, cmd)()
Run Code Online (Sandbox Code Playgroud)