如何在字典中分配函数?

时间:2010-05-08 15:34:07

标签: python

我遇到了一个我编写的简单程序的问题,我想根据用户输入执行某个功能。我已经使用字典作为交换机的替代来进行分配但是当我尝试将字符分配给字典时它不会执行它们... 代码:

def PrintValuesArea():
    ## do this
def PrintValuesLength():
    ## do that
def PrintValuesTime():
    ## do third

PrintTables={"a":PrintValuesArea,"l":PrintValuesLength,"t":PrintValuesTime}
PrintTables.get(ans.lower()) ## ans is the user input

我做错了什么?它看起来和我见过的所有例子都一样......

1 个答案:

答案 0 :(得分:10)

你忘记打电话了。

PrintTables.get(ans.lower())()

PrintTables[ans.lower()]()