Python: Using a dictionary as switch not working
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 evalua开发者_运维百科tes 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.
You shouldn't call the functions. Just store the function objects itself in the dictionary, not their return values:
def keyboard(key):
values = {
110: discoMode,
27: exit
}
values.get(key, default)()
f()
is a call to the function f
and evaluates to the return value of this call. f
is the function object itself.
def keyboard(key):
values = {
110: discoMode(),
27: exit()
}
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:
def keyboard(key):
values = {
110: discoMode,
27: exit
}
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".
def keyboard(key):
values = {
110: discoMode,
27: exit
}
values.get(key, default)()
精彩评论