python中有没有switch_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代碼的對分支情況的處理方式比switch語句要更加簡潔,但是我也可以認為它更晦澀難懂。我剛開始寫Python代碼的時候,總覺得怪怪的。后來時間長了,使用字典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?語句來處理這些問題”。而且還能使用字典映射到函數,分派到類方法。
令人疑惑的是,官方只給出了替代方案,而并沒有解釋為什么。換句話說,就是“無可奉告“。在我看來,官方想要表達的意思其實就是”Python不需要case語句“。
真相是什么?
然而我聽得最多的說法是,switch/case語句非常難以調試。
但是稍微思考一下就知道這種說法是站不住腳的。只需要假想一下,你使用了一個重重嵌套的巨大字典用來處理分支邏輯;如果這個字典元素超過了100個,那么它的調試難度其實并不低于100個case語句。
或許因為字典映射速度更快?
然并卵,Python沒有switch/case語句,沒法測試,跳過這一點。
Python這種做法的巨大優勢
經驗之談,我經常會碰到一些情景,Python的做法比switch/case語句要優雅有效的多,那就是在我需要在運行時增刪映射項的時候。碰到需要這么做的時候,我的Python技能就碉堡了,可以動態的改變字典映射和類方法分派調用。有了這些心得之后,我在也沒有懷念過switch/case語句。
最終章
對我而言,使用Python的經驗迫使我使用字典映射,而我亦從中因禍得福。沒有switch/case語句的苦惱使得我產生了以前沒有過的想法、實現了以前沒開發過的功能。
總而言之,Python switch/case語句的缺失,使我成為了更好的程序員;而這種開發生態,就是我所期望的比“官方解釋”更好的答案。
總結
以上是生活随笔為你收集整理的python中有没有switch_Python为什么没有switch/case语句?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 3.0 print_Pyt
- 下一篇: python基础知心得总结_【pytho