Python学习(20):字典替代Swi

发布时间:2019-08-14 12:47:59编辑:auto阅读(1508)

    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)() #打印:输入错误啦。。。。

关键字