Python不像C/C++,Java等有switch-case的语法。不过其这个功能,比如用Dictionary以及lambda匿名函数特性来替代实现。 比如PHP中的如下代码: 1 2 3 4 5 6 7 8 9 10 11 | switch ( $value ) {
case 'a' :
$result = $x * 5;
break ;
case 'b' :
$result = $x + 7;
break ;
case 'c' :
$result = $x - 2;
break ;
}
|
Python的等价实现为: 1 2 3 4 5 | result = {
'a' : lambda x: x * 5 ,
'b' : lambda x: x + 7 ,
'c' : lambda x: x - 2
}[value](x)
|
如果是稍微复杂一点的函数,也可以做到,比如我们计算加减乘除,函数定义如下: 1 2 3 4 5 6 7 8 | def add(a,b):
return a + b
def multi(a,b):
return a * b
def sub(a,b):
return a - b
def div(a,b):
return a / b
|
如果是switch实现的话,case(‘操作数’)来判断之行的对应函数。看看Python的实现: 1 2 3 4 5 6 7 8 9 10 11 | def calc( type ,x,y):
calculation = { '+' : lambda :add(x,y),
'*' : lambda :multi(x,y),
'-' : lambda :sub(x,y),
'/' : lambda :div(x,y)}
return calculation[ type ]()
result1 = calc( '+' , 3 , 6 )
result2 = calc( '-' , 3 , 6 )
print result1, result2
|
这里用的结构如下: 1 2 3 4 | message = { 'type 1 ' : lambda : func 1 ( some_data ) ,
'type 2 ' : lambda : func 2 ( other_data ) ,
}
return message [type] ( )
|
还有更加复杂的就是自定义一个Switch类了,可以参考http://code./recipes/410692-readable-switch-construction-without-lambdas-or-di/
|