函数名称为字符串

0 python string function

我有三个函数,名为Aufgabe [1,2,3].我想这样做,如果有人进入控制台"1" Aufgabe1被触发等等.有可能吗?

AufgabenNummer = int(input("Welche Aufgabe willst du öffnen?\n"))
    Aufgabe = "Aufgabe" + str(AufgabenNummer)
    Aufgabe()

def Aufgabe1():
    zahl1 = int(input("Erste Zahl...?\n"))
    zahl2 = int(input("Zweite Zahl...?\n"))
    print (str(zahl1) + "+" + str(zahl2) + "=" + str(zahl1+zahl2))

def Aufgabe2():
    for i in range(0,11):
        print(i)

def Aufgabe3():
    name = int(input("Hallo wie heißt du?\n"))
    print ("Hallo" + str(name))
Run Code Online (Sandbox Code Playgroud)

Cha*_* S. 7

执行此操作的最佳方法是维护名称/功能对的字典:

function_table = {
   'Aufgabe3' : Aufgabe3,
   'Aufgabe2' : Aufgabe2,
   'Aufgabe1' : Aufgabe1,
}
Run Code Online (Sandbox Code Playgroud)

然后通过在表中查找来调用相应的函数

function_table['Aufgabe1']()
Run Code Online (Sandbox Code Playgroud)

这使您可以更精细地控制输入到函数的映射,从而允许您在不更改程序界面的情况下自由重构.