1. 程式人生 > >為什麼Python中沒有Switch/Case語句?

為什麼Python中沒有Switch/Case語句?

不同於我用過的其它程式語言,Python 沒有 switch / case 語句。為了實現它,我們可以使用字典對映:

def numbers_to_strings(argument):
switcher = {
    0: "zero",
    1: "one",
    2: "two",
}
return switcher.get(argument, "nothing")

這段程式碼類似於:

function(argument){
switch(argument) {
    case 0:
        return "zero";
    case 1:
        return
"one"; case 2: return "two"; default: return "nothing"; }; };

Python 程式碼通常比處理 case 的標準方法更為簡短,也可以說它更難理解。當我初次使用 Python 時,感覺很奇怪並且心煩意亂。而隨著時間的推移,在 switch 中使用字典的 key 來做識別符號變得越來越習以為常。

函式的字典對映

在 Python 中字典對映也可以包含函式或者 lambda 表示式:

def zero():
return "zero"

def one():
return "one"
def numbers_to_functions_to_strings(argument): switcher = { 0: zero, 1: one, 2: lambda: "two", } # Get the function from switcher dictionary func = switcher.get(argument, lambda: "nothing") # Execute the function return func()

雖然 zero 和 one 中的程式碼很簡單,但是很多 Python 程式使用這樣的字典對映來排程複雜的流程。

類的排程方法

如果在一個類中,不確定要使用哪種方法,可以用一個排程方法在執行的時候來確定。

class Switcher(object):
    def numbers_to_methods_to_strings(self, argument):
        """Dispatch method"""
        # prefix the method_name with 'number_' because method names
        # cannot begin with an integer.
        method_name = 'number_' + str(argument)
        # Get the method from 'self'. Default to a lambda.
        method = getattr(self, method_name, lambda: "nothing")
        # Call the method as we return it
        return method()

    def number_0(self):
        return "zero"

    def number_1(self):
        return "one"

    def number_2(self):
        return "two"

很靈活,對吧?

官方說明

官方的解釋說,“用if… elif… elif… else序列很容易來實現 switch / case 語句”。而且可以使用函式字典對映和類的排程方法。

可以說官方的說明並沒有解釋什麼,只是給出瞭解決方案。換句話說,沒有回答為什麼。我認為其實官方真正想說的是:“Python 不需要 switch / case 語句”。

真的是這樣嗎?

是的。但是還有別的原因。我聽牛人說過,在程式碼中 switch/case 語句真的很難除錯。

就我個人而言,我發現當執行到大量巢狀的用作程式碼分支對映的字典裡,上述說法就站不住腳了。想想吧,一個超過100條語句的巢狀字典,和一個巢狀100個以上 case 的 switch/case 程式碼塊一樣,都是難以除錯的。

字典對映執行更快?

Python 沒有 case 語句,使用其它語言的衡量標準是沒有意義的,因為在某種語言中執行更快並不意味著在另一種語言中也一樣。讓我們繼續。

Python 實現方法的顯著優點

有時候我會遇到 Python 的實現方法比 switch/case 語句更好用的情況,例如在執行的時候,需要從對映裡新增或者刪除一些潛在的選項。每當這時,多年來使用字典對映和排程方法的實踐讓我受益匪淺。現在我覺得,我再也無法回到依賴 switch/case 語句的日子了。

結束語

Python 迫使我積累了很多對映的實踐經驗,對我來說是塞翁失馬,焉知非福。沒有 switch/case 語句可用的約束,促使我想到了可能不會用來開發的方法和主意。

有意或無意中,Python 沒有 switch/case 語句已成為一種社會建構,並讓我成為一個更優秀的程式設計師。

綜上所述,所以我認為這種意外的社會構建解釋比官方的“用這個來代替”的說明要好得多。

相關推薦

為什麼Python沒有Switch/Case語句?

不同於我用過的其它程式語言,Python 沒有 switch / case 語句。為了實現它,我們可以使用字典對映: def numbers_to_strings(argument): switcher = { 0: "zero", 1:

Javaswitch-case語句

sub public return ID PE stat class a case cti class ArithmeticFunction {   public static int arithmetic(int a, int b, String operator) {

react使用switch-case語句

在週期中使用switch-case switch(this.state.color){ case "1":return <img src={gift1}/>; break;

C語言中switch...case語句break的重要性

不能 實現 比例 重要性 case語句 毫無 ... 應該 switch 在C語言中switch...case語句是經常用到的,下面我介紹一下在使用該語句時候需要註意的一個細節問題。話不多說,直接舉例子: 例子1: switch(fruit) { case 1:printf

Switch Case語句多個值匹配同一個代碼塊的寫法

har com arch mssql pre html www ase cas switch ($p) { case ‘home‘: case ‘‘: $current_home = ‘current‘; break

switch case語句能否作用在String,long上

bsp lips case語句 nbsp string 類型 span 出了 byte 在之前的eclipse中使用switch的case語句時是只能為(byte,short,char)int類型或枚舉類型。但在jdk1.7以後 在case語句中是可以使用String 以

Python 類似switch/case語句實現方法 獲取文件內容匹配函數並執行

lin get err 容易 main ref 設計 case error 這個主要提供了一種思路,這個不太好理解,我徹底敲了一遍,心裏有點低。參考下面的文章標題:Python switch/case語句實現方法來源:https://blog.csdn.net/l46013

Python 實現簡單的 switch/case 語句

在Python中是沒有Switch / Case語句的,很多人認為這種語句不夠優雅靈活,在Python中用字典來處理多條件匹配問題字典會更簡單高效,對於有一定經驗的Python玩家不得不承認,的確如此。 但今天我們還是來看看如果一定要用Python來Switch /

C語言switch case語句定義變數問題

這個問題需要分開討論,C 語言和 C++ 的標準定義是不同的。 C++ int Caset(int a) { switch (a) { case 1: int b = 1; st

在Android library不能使用switch-case語句訪問資源ID的原因分析及解決方案

報錯是因為case分支後面跟的引數必須是常數,也就是說library中的R.java的資源ID不是常數, public static final class animator { public static int design_appbar_state_list_animator = 0x7f020

iOSswitch case語句裡面不能定義物件,有語法錯誤,除非加一個花括號

最近發現一個問題呢 發現在switch的case裡面不能去定義物件了,一定義物件就會報錯了 仔細瞭解了一下在C或者C++中,只要是在任何一對花括號 “{ }”中定義的物件,那麼該物件的作用域就侷限在這對花括號裡面,上面的程式碼的錯誤就出現在這兒了。 switch (i) {          

switch case 語句能否使用continue關鍵字?為什麼?

  毋庸置疑,在switch case 語句中不能使用continue 關鍵字。continue語句的作用是跳出本次迴圈,轉入執行下一次迴圈。故而,continue語句只能用於迴圈語句中,而switch case語句為多分支選擇語句,不是迴圈語句,所以在switch case

Python switch/case語句實現方法

與Java、C\C++等語言不同,Python中是不提供switch/case語句的,這一點讓我感覺到很奇怪。我們可以通過如下幾種方法來實現switch/case語句。 使用if…elif…elif…else 實現switch/case 可以使用if…e

switchcase 語句的用法

[] other sta rgs bsp str 復制代碼 ring 表達 public class Test7 { public static void main(String[] args) { int i=5; switch

20:python的循環語句

python 數據分析 ubuntu linux 人工智能 機器學習20.1 while語句問題描述: 求5!。提示: 求5的階乘,即5*4*3*2*1 我總覺得不直觀,我想最後打印的是形如:5!= 5*4*3*2*1 =

Python使用循環語句打印三角形、菱形

size 不能 div 16px 作用 blog 部分 == gre 前言:在學習開發語言循環語句的使用過程中,經常會打印各種形狀來驗證對循環語句的熟練掌握程度,接下來就使用python來打印多種形狀練習。 如下示例中:變量i用於控制外層循環(圖形行數),j用於控制空格的個

JavaScript基礎知識(if、if else、else if、while、switch...case語句

case語句 bubuko ... gpo 控制 java 包含 分享 if...else 13、語句 概念:就是分號(;) 代表一條語句的結束 習慣:一行只編寫一條語句;一行編寫多條語句(代碼可讀性較差) 語句塊:可以包含多條語句 "{ }"將多條語句包裹 u 條

react jsx 使用 switch case 示例

fault platform ems urn span 淘寶 for cas 愛奇藝 <div> <span>適用平臺:</span> <span>{(() => { switch (currentItems.

(策略模式+工廠模式+map)套餐 Kill 專案switch case

接手新任務:接入第三家存證機構,看之前的程式碼使用了swith case判斷使用哪家存證機構,每家存證機構的實現邏輯不一樣 程式碼的壞味道:多層swich case。多層swich case不好維護,是時候應該重構了, 優化前的程式碼 為了便於理解,舉個沒有業務邏輯的例子,基於這個例子上進行優化

ST語言和C語言關於case of 和switch case語句的區別

C語言中,case後不可直接跟多個常量,要如下圖所示使用(不要忘記defalut) switch(int,char){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: //todo break; defalut: br