Python:使用字典作为开关不起作用
我是一个“Python 新手”,试图掌握字典数据类型的内部工作原理。昨晚我试图在 openGL 程序上使用一个控制结构(即 switch 语句)进行键盘输入。
问题是,由于某种原因,字典不断评估所有情况(本例中为两个),而不是仅评估按键中的情况。
这是一段示例代码:
def keyboard(key):
values = {
110: discoMode(),
27: exit()
}
values.get(key, default)()
昨晚我花了一个小时或更长时间试图找到为什么评估每个“案例”的答案,我有一些想法,但无法清楚地找到问题的答案“为什么”的问题。
那么,有人可以向我解释为什么当我按下“n”键(ascii 表示为 110)时,这段代码也会评估 27(ESC 键)下的条目吗?
如果这个话题已经被打死了,我深表歉意,但我查了一下,无法轻松找到明确的答案(也许我错过了)。
谢谢。
I'm a 'python neophyte' and trying to grasp the inner workings of the dictionary datatype. Last night I was attempting to use one as a control structure (i.e. switch statement) for keyboard input on an openGL program.
The problem was that for some reason the dictionary kept evaluating ALL cases (two in this instance) instead of just the one from the key pressed.
Here is an example piece of code:
def keyboard(key):
values = {
110: discoMode(),
27: exit()
}
values.get(key, default)()
I spent an hour or more last night trying to find the answer to why every 'case' is evaluated, I've got a few ideas, but wasn't able to clearly find the answer to the "why" question.
So, would someone be kind enough to explain to me why when I hit the 'n' key (the ascii representation is 110) that this piece of code evaluates the entry under 27 (the ESC key) too?
Apologize if this topic has been beaten to death but I looked and was unable to find the clear answer easily (maybe I missed it).
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应该调用这些函数。只需将函数对象本身存储在字典中,而不是它们的返回值:
f()
是对函数f
的调用,并计算出此调用的返回值。f
是函数对象本身。You shouldn't call the functions. Just store the function objects itself in the dictionary, not their return values:
f()
is a call to the functionf
and evaluates to the return value of this call.f
is the function object itself.在本例中,您正在构建一个字典,其中包含分配给 110 的“discoMode()”返回值,以及分配给 27 的“exit()”返回值。
您要编写的内容是:
它将把 110 分配给函数discoMode(不调用该函数!),同样用于退出。请记住,函数是第一类对象:可以对它们进行赋值、存储和从其他变量调用。
In this case, you are building a dict containing the return value of "discoMode()" assigned to 110, and the return value of "exit()" to 27.
What you meant to write was:
Which will assign 110 to the function discoMode (not call the function!), likewise for exit. Remember functions are first class objects: they can be assigned, stored, and called from other variables.
只需删除括号,这样您就可以引用函数而不是函数调用的结果。否则,您明确地说:“调用此函数以获取与此键关联的值”。
Just remove the parentheses, so you reference the function instead of the result of the call to the function. Otherwise, you explicitly say: "call this function to get the value to associate to this key".