国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

Python實現(xiàn)switch/case語句

瀏覽:121日期:2022-07-28 11:03:39
目錄使用if…elif…elif…else 實現(xiàn)switch/case使用字典 實現(xiàn)switch/case在類中可使用調(diào)度方法實現(xiàn)switch/case總結(jié)使用if…elif…elif…else 實現(xiàn)switch/case

可以使用if…elif…elif..else序列來代替switch/case語句,這是大家最容易想到的辦法。但是隨著分支的增多和修改的頻繁,這種代替方式并不很好調(diào)試和維護(hù)。

使用字典 實現(xiàn)switch/case

可以使用字典實現(xiàn)switch/case這種方式易維護(hù),同時也能夠減少代碼量。如下是使用字典模擬的switch/case實現(xiàn):

def num_to_string(num): numbers = {0 : 'zero',1 : 'one',2 : 'two',3 : 'three' } return numbers.get(num, None)if __name__ == '__main__': print num_to_string(2) print num_to_string(5)

執(zhí)行結(jié)果如下:

twoNone

Python字典中還可以包括函數(shù)或Lambda表達(dá)式,代碼如下:

def success(msg): print msgdef debug(msg): print msgdef error(msg): print msgdef warning(msg): print msgdef other(msg): print msgdef notify_result(num, msg): numbers = {0 : success,1 : debug,2 : warning,3 : error } method = numbers.get(num, other) if method:method(msg)if __name__ == '__main__': notify_result(0, 'success') notify_result(1, 'debug') notify_result(2, 'warning') notify_result(3, 'error') notify_result(4, 'other')

執(zhí)行結(jié)果如下:

successdebug warning errorother

通過如上示例可以證明能夠通過Python字典來完全實現(xiàn)switch/case語句,而且足夠靈活。尤其在運(yùn)行時可以很方便的在字典中添加或刪除一個switch/case選項。

在類中可使用調(diào)度方法實現(xiàn)switch/case

如果在一個類中,不確定要使用哪種方法,可以用一個調(diào)度方法在運(yùn)行的時候來確定。代碼如下:

class switch_case(object): def case_to_function(self, case):fun_name = 'case_fun_' + str(case)method = getattr(self, fun_name, self.case_fun_other)return method def case_fun_1(self, msg):print msg def case_fun_2(self, msg):print msg def case_fun_other(self, msg):print msgif __name__ == '__main__': cls = switch_case() cls.case_to_function(1)('case_fun_1') cls.case_to_function(2)('case_fun_2') cls.case_to_function(3)('case_fun_other')

執(zhí)行結(jié)果如下:

case_fun_1case_fun_2case_fun_other

總結(jié)

就個人來說,使用字典來實現(xiàn)switch/case是最為靈活的,但是理解上也有一定的難度。

本篇文章就到這里了,希望能給你帶來幫助,也希望您能夠多多關(guān)注好吧啦網(wǎng)的更多內(nèi)容!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 凤翔县| 额敏县| 油尖旺区| 柳河县| 永德县| 昭觉县| 西乌珠穆沁旗| 军事| 政和县| 吉首市| 修水县| 垣曲县| 凌云县| 扬中市| 安阳县| 连城县| 南部县| 邻水| 颍上县| 长宁区| 东安县| 昆山市| 梁河县| 白朗县| 淳化县| 罗江县| 阿克苏市| 瓮安县| 闵行区| 蛟河市| 资源县| 东山县| 来安县| 澳门| 白沙| 绥江县| 涿州市| 博客| 黑山县| 苍山县| 邹平县|