您的位置:首页 > 编程语言 > Python开发

python 中的"switch"用法

2018-01-09 09:58 218 查看

转载:http://python.jobbole.com/82008/

为什么Python中没有Switch/Case语句?

不同于我用过的其它编程语言,Python 没有 switch / case 语句。为了实现它,我们可以使用字典映射:

  Python
def switch_test_item(item):
switcher = {
"CPU": 0,
"Memory":1,
"BIOSVER":2,
"FAN":3,
"BIOSSETUP":4,
}
return switcher.get(item,"nothing")

这段代码类似于:

 function(item){   switch(item){     case "CPU":       return 0;     case "Memory":       return 1;     case "BIOSVER":2:         return:3      ......      default:         return "nothing";   } } 

函数的字典映射

在 Python 中字典映射也可以包含函数或者 lambda 表达式:

        Python  
  def zero():     return "zero"   def one():     return "one"   def numbers_to_functions_to_strings(argument):     switcher = {         0: zero,         1: one,         2: lambda: "two",     }     # Get the function from switcher dictionary     func = switcher.get(argument, lambda: "nothing")     # Execute the function     return func()

虽然 

zero
 和 
one
 中的代码很简单,但是很多 Python 程序使用这样的字典映射来调度复杂的流程。

example:

def switch_test_item(item, index_b,exename,version,vercheck):
switcher = {
"CPU": CPU_TEST,
"Memory":MEMORY_TEST,
"BIOSVER":BIOSVER_TEST,
"FAN":FAN_TEST,
}
return switcher[item](index_b,exename,version,vercheck)
def CPU_TEST(index_b,exename,version,vercheck):
{
...
}

然后switch_test_item就把index_b,exename,version,vercheck都传递给CPU_TEST等功能函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: