Re: [問題] 怎麼用 Python 寫出 switch 的功能?

看板Python作者 (lizka)時間7年前發表 (2017/10/19 07:55), 7年前編輯推噓0(002)
留言2則, 2人參與, 7年前最新討論串3/11 (看更多)
※ 引述《kenduest (小州)》之銘言: : ※ 引述《henry8168 (番薯猴)》之銘言: : : switch(errfunc){ : : case "init_process3": : : release_process2(); : : case "init_process2": : : release_process1(); : : case "init_process1": : : printf("%s: initial failed.\n",errfunc); : : } : : return -1; : : } : : 抱歉,在 Python 板打這麼多 C 語言 @@" : : 不過我想表達的就如同上述,請問 Python 該怎麼做到類似的功能呢? : : 我正在改一位同仁的 Python,想運用類似 switch 的特點完成。 : : 查到很多人都說可以用 dict,卻還是一頭霧水。 : : 謝謝。 : 類似這個方式嗎? : entry = { "init_process3": release_process2, : "init_process2": release_process1, : "init_process2": initial_fail, : } : handler = entry.get(errfunc) : if handler: : handler() : return -1 修改後,有保證順序。 from collections import OrderedDict entry = OrderedDict() entry["init_process3"] = release_process2 entry["init_process2"] = release_process1 entry["init_process1"] = initial_fail keys = list(iter(entry)) if errfunc not in entry: return -1 start = keys.index(errfunc) for i in range(start, len(keys)): entry.get(keys[i])() 我對op的理解是滿足某個條件後執行一系列commad command的順序是"固定", 條件的存在是為了找出從哪個command開始做。 因此,也可以是: commands = [release_process2, release_process1, "break", initial_fail] cases = {"initial_process3": 0, "initial_process2": 1} try: start = cases[errfunc] except KeyError: return -1 else: for command in commands[start:]: try: command() except TypeError: break 然後可以再包成class或function,變形可以有很多種。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 180.204.51.251 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1508399730.A.943.html ※ 編輯: lizkarina (180.204.51.251), 10/19/2017 15:56:24

10/19 16:15, 7年前 , 1F
這樣沒有保證順序會是init_process3, 2, 1吧
10/19 16:15, 1F
※ 編輯: lizkarina (180.204.51.251), 10/19/2017 16:16:37

10/19 16:20, 7年前 , 2F
對,要修一下。
10/19 16:20, 2F
※ 編輯: lizkarina (180.204.48.228), 10/19/2017 18:06:08 ※ 編輯: lizkarina (180.204.48.228), 10/19/2017 18:50:50 ※ 編輯: lizkarina (180.204.48.228), 10/19/2017 18:51:19
文章代碼(AID): #1Pw5fob3 (Python)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 11 篇):
文章代碼(AID): #1Pw5fob3 (Python)