不同于我用过的其它编程语言,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"