Python开关案例 [英] Python switch case
问题描述
我试图在python上使用字典作为switch case,但是,参数似乎没有传递给被调用的函数,请帮忙:
I am trying to use dictionary as switch case on python, however, the parameter does not seem to be pass to the called function, please help:
def switchcase(num,cc):
def fa(num):
out= num*1.1;
def fb(num):
out= num*2.2;
def fc(num):
out= num*3.3;
def fd(num):
out= num*4.4;
options = {
"a":fa(num),
"b":fb(num),
"c":fc(num),
"d":fd(num)
}
out=0
options[cc];
return out
print switchcase(10,"a")
输出为0,我没弄清楚问题
the output is 0, I could not figure out the problem
推荐答案
问题是:
out=0
options[cc];
return out
基本上 -- 无论 options[cc]
给你什么,你都会返回 0
因为这是 out
的值.请注意,在各种fa
、fb
、...函数中设置out
不会不改变out
在调用者中.
Basically -- no matter what options[cc]
gives you, you're going to return 0
because that's the value of out
. Note that setting out
in the various fa
, fb
, ... functions does not change the value of out
in the caller.
您可能想要:
def switchcase(num,cc):
def fa(num):
return num*1.1;
def fb(num):
return num*2.2;
def fc(num):
return num*3.3;
def fd(num):
return num*4.4;
options = {
"a":fa(num),
"b":fb(num),
"c":fc(num),
"d":fd(num)
}
return options[cc];
另请注意,这在实践中效率极低.每次调用 switchcase
时,您都会创建 4 个函数(并分别调用).
Also note that this will be horribly inefficient in practice. You're creating 4 functions (and calling each) every time you call switchcase
.
我猜您实际上想要创建一个预制的函数映射.然后你可以从地图中选择你真正想要的函数并用给定的数字调用它:
I'm guessing that you actually want to create a pre-made map of functions. Then you can pick up the function that you actually want from the map and call it with the given number:
def fa(num):
return num*1.1
def fb(num):
return num*2.2
def fc(num):
return num*3.3
def fd(num):
return num*4.4
OPTIONS = {
"a":fa,
"b":fb,
"c":fc,
"d":fd
}
def switchcase(num,cc):
return OPTIONS[cc](num)
这篇关于Python开关案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!