Python中如何实现Switch/Case语句?
- 2019 年 11 月 20 日
- 筆記
01
跟其它语言有所区别,Python中并没有Switch/Case语句。那么,该如何实现Switch/Case语句呢?
我们通过一个示例看。将数字1,2,3,4映射为Spring,Summer,Fall,Winter,而其它数字映射为Invalid Season。Java代码中可以用Switch/Case语句来实现:
public static String getSeason(int season) { String SeasonName = ""; switch (season) { case 1: SeasonName = "Spring"; break; case 2: SeasonName = "Summer"; break; case 3: SeasonName = "Fall"; break; case 4: SeasonName = "Winter"; break; default: SeasonName = "Invalid Season"; break; } return SeasonName; }
而Python中没有Switch/Case语句,那么该如何实现呢?
应该有两种实现方式,第一种是通过 if… elif… elif… else 来实现,大家应该比较熟悉,代码如下:
def getSeason(season): """ 将season映射为字符串 :param season: :return: """ if season == 1: return "Spring" elif season == 2: return "Summer" elif season == 3: return "Fall" elif season == 4: return "Winter" else: return "Invalid Season"
第二种方式,也是比较好的一种方式,小编极力推荐的一种方式,也是更Pythonic的一种写法,是通过字典(dict)来进行实现的:
seasondict = { 1: "Spring", 2: "Summer", 3: "Fall", 4: "Winter" } def getSeason(season): """ 将season映射为字符串 :param season: :return: """ return seasondict.get(season, "Invalid Season")
是不是代码更为简洁易懂?
那么,如果case中是执行不同的方法,而不是简单的返回字符串,有没有办法实现呢?
答案是必须的,可以通过 if… elif… elif… else 来实现,其中的每个分支调用不同的函数,这里不再赘述。也可以通过字典来实现的,主要看一下字典的实现方式:
def Season1(): return "Spring" def Season2(): return "Summer" def Season3(): return "Fall" def Season4(): return "Winter" def Default(): return "Invalid Season" seasondict = { 1: Season1, 2: Season2, 3: Season3, 4: Season4 } def getSeason(season): """ 将season映射为字符串 :param season: :return: """ fun = seasondict.get(season, Default) return fun()
这种方式需要单独定义dict来完成函数的映射,还有一种方式,即通过在类中定义不同的方法(方法名有一定的规则),然后通过getattr函数来进行实现,代码如下:
class Season(): def Season1(self): return "Spring" def Season2(self): return "Summer" def Season3(self): return "Fall" def Season4(self): return "Winter" def Default(self): return "Invalid Season" def getSeason(self, season): """ 将season映射为字符串 :param season: :return: """ season_name = "Season" + str(season) fun = getattr(self, season_name, self.Default) return fun()
Python中的这些实现Swith/Case的方法你都清楚了吗?
本文来自公众号:python那些事
文部分来源网络,如有侵权请第一时间联系删除。