Python switch/case語句實現方法
阿新 • • 發佈:2019-02-11
與Java、C\C++等語言不同,Python中是不提供switch/case語句的,這一點讓我感覺到很奇怪。我們可以通過如下幾種方法來實現switch/case語句。
使用if…elif…elif…else 實現switch/case
可以使用if…elif…elif..else序列來代替switch/case語句,這是大家最容易想到的辦法。但是隨著分支的增多和修改的頻繁,這種代替方式並不很好除錯和維護。
使用字典 實現switch/case
可以使用字典實現switch/case這種方式易維護,同時也能夠減少程式碼量。如下是使用字典模擬的switch/case實現:
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)
執行結果如下:
two
None
Python字典中還可以包括函式或Lambda表示式,程式碼如下:
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")
執行結果如下:
success
debug
warning
error
other
通過如上示例可以證明能夠通過Python字典來完全實現switch/case語句,而且足夠靈活。尤其在執行時可以很方便的在字典中新增或刪除一個switch/case選項。
在類中可使用排程方法實現switch/case
如果在一個類中,不確定要使用哪種方法,可以用一個排程方法在執行的時候來確定。程式碼如下:
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")
執行結果如下:
case_fun_1
case_fun_2
case_fun_other
總結
就個人來說,使用字典來實現switch/case是最為靈活的,但是理解上也有一定的難度。