python 数据类型 之 利用 dict 模仿 switch语句功能

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






class Switch:
switch = None

@classmethod
def switch(cls, day):
switchDic = {"Sunday": cls.casetaskForRest,
"Monday": cls.casetaskForChinese,
"Tuesday": cls.casetaskForMath,
"Wednesday": cls.casetaskForEnglish,
"Tursday": cls.casetaskForEnglish,
"Friday": cls.casetaskForEnglish,
"Saturday": cls.casetaskForRest
}
cls.switch = switchDic.get(day, cls.casetaskForDefault)()
return cls.switch

@staticmethod
def casetaskForSunday():
print("今天休息")

@staticmethod
def casetaskForRest():
print("今天休息")

@staticmethod
def casetaskForChinese():
print("今天上语文课")

@staticmethod
def casetaskForMath():
print("今天上数学课")

@staticmethod
def casetaskForEnglish():
print("今天上英语课")

@staticmethod
def casetaskForDefault():
print("输入错误啦。。。。")


Switch.switch('Sunday')
 

转载于:https://www.cnblogs.com/yanxiatingyu/p/9277974.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值