码迷,mamicode.com
首页 > 编程语言 > 详细

python 利用 dict 模仿 switch语句功能

时间:2018-07-07 20:46:24      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:代码   dea   default   val   format   tty   function   chinese   word   

Python本身并不提供Switch的语法功能,为了能够解决类似switch分支需求的问题,我们可以使用字典代替实现。 
解决思路:

  1. 利用字典取值的get方法的容错性,处理switch语句中的default情况
  2. 设置字典的vlaue为对应方法名,来代替switch语句中的代码块
  3. 为不同key设置相同的value,模拟switch中穿透
def taskForSunday():
    print("今天休息")
def taskForRest():
    print("今天休息")
def taskForChinese():
    print("今天上语文课")
def taskForMath():
    print("今天上数学课")
def taskForEnglish():
    print("今天上英语课")
def taskForDefault():
    print("输入错误啦。。。。")

switchDic = {"Sunday":taskForRest,
            "Monday":taskForChinese,
            "Tuesday":taskForMath,
            "Wednesday":taskForEnglish,
            "Tursday":taskForEnglish,
            "Friday":taskForEnglish,
            "Saturday":taskForRest
}

 

 

1.测试取值

通过get获取字典key对应的方法后,又添加了个括号,这样会执行得到的方法

day1 = "Monday"
switchDic.get(day1,taskForDefault)() #打印:今天上语文课

 

2.测试穿透

##Wednesday,Tursday,Friday三个的效果相同
day2 = "Friday"
switchDic.get(day2,taskForDefault)()  #打印:今天上英语课

 

3.测试Deault效果

#字典的get方法第二个参数是默认值,即通过key值不能找到value时,返回默认值
#这里使用了自定义函数的函数名:taskForDefault,用于实现switch的defalut功能
day3 = "天气不错哦"
switchDic.get(day3,taskForDefault)() #打印:输入错误啦。。。。

python 利用 dict 模仿 switch语句功能

标签:代码   dea   default   val   format   tty   function   chinese   word   

原文地址:https://www.cnblogs.com/yanxiatingyu/p/9277974.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!