可以使用if…elif…elif..else序列來(lái)代替switch/case語(yǔ)句,這是大家最容易想到的辦法。但是隨著分支的增多和修改的頻繁,這種代替方式并不很好調(diào)試和維護(hù)。
可以使用字典實(shí)現(xiàn)switch/case這種方式易維護(hù),同時(shí)也能夠減少代碼量。如下是使用字典模擬的switch/case實(shí)現(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é)果如下:
two
None
Python字典中還可以包括函數(shù)或Lambda表達(dá)式,代碼如下:
def success(msg): print msg def debug(msg): print msg def error(msg): print msg def warning(msg): print msg def other(msg): print msg def 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é)果如下:
success
debug warning error
other
通過(guò)如上示例可以證明能夠通過(guò)Python字典來(lái)完全實(shí)現(xiàn)switch/case語(yǔ)句,而且足夠靈活。尤其在運(yùn)行時(shí)可以很方便的在字典中添加或刪除一個(gè)switch/case選項(xiàng)。
如果在一個(gè)類中,不確定要使用哪種方法,可以用一個(gè)調(diào)度方法在運(yùn)行的時(shí)候來(lái)確定。代碼如下:
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 msg if __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_1
case_fun_2
case_fun_other
就個(gè)人來(lái)說(shuō),使用字典來(lái)實(shí)現(xiàn)switch/case是最為靈活的,但是理解上也有一定的難度。
本篇文章就到這里了,希望能給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
標(biāo)簽:濰坊 辛集 贛州 渭南 西安 七臺(tái)河 許昌 雅安
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python實(shí)現(xiàn)switch/case語(yǔ)句》,本文關(guān)鍵詞 Python,實(shí)現(xiàn),switch,case,語(yǔ)句,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。