Python本身并不提供Switch的语法功能,为了能够解决类似switch分支需求的问题,我们可以使用字典代替实现。
解决思路:
- 利用字典取值的get方法的容错性,处理switch语句中的default情况
- 设置字典的vlaue为对应方法名,来代替switch语句中的代码块
- 为不同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')