简体   繁体   English

如何在字典中分配函数?

[英]How do I assign functions in a dictionary?

I'm having a problem with a simple program I wrote, I want to perform a certain function according to the users input. 我遇到一个我编写的简单程序的问题,我想根据用户输入执行某个功能。 I've already used a dictionary as a replacement for a switch to do assignment but when I try to assign functions to the dictionary it doesn't execute them... The code: 我已经使用字典作为交换机的替代来进行分配,但是当我尝试将字符分配给字典时,它不会执行它们...代码:

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

what did I do wrong? 我做错了什么? It looks the same as all the examples I've seen.... 它看起来和我见过的所有例子都一样....

You forgot to call it. 你忘了叫它。

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

or 要么

PrintTables[ans.lower()]()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM