Python 類似switch/case語句實現方法 獲取文件內容匹配函數並執行
阿新 • • 發佈:2018-10-18
lin get err 容易 main ref 設計 case error 這個主要提供了一種思路,這個不太好理解,我徹底敲了一遍,心裏有點低。參考下面的文章
標題:Python switch/case語句實現方法
來源:https://blog.csdn.net/l460133921/article/details/74892476
標題:Python switch/case語句實現方法
來源:https://blog.csdn.net/l460133921/article/details/74892476
與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實現:
#!/usr/bin/python # -*- coding: utf-8 -*- def zkper(msg): print msg print ("zkper函數") def scp(msg): print msg print ("scp函數") def cou(msg): print msg print ("cou函數") def error(msg): print msg print ("error函數") def other(msg): print msg print (msg+"不更新") def notify_result(num, msg): numbers = { ‘zkper=1‘ : zkper, ‘scp=1‘ : scp, ‘cou=1‘ : cou, 3 : error } method = numbers.get(num, other) if method: method(msg) def update_all_aw(): for line in open("upmips.cfg"): a=line.strip() # print(a) if __name__ == "__main__": notify_result(a, a) print ("===") update_all_aw()
umpips.cfg的內容為
zkper=1
scp=1
cou=0
bjs=0
設計思路,=1的更新該函數,=0表示不更新。
裏面使用了逐行讀取配合字典函數來達到效果。
Python 類似switch/case語句實現方法 獲取文件內容匹配函數並執行