Python下Switch-Case的几种应用
2年前 • 756次点击 • 来自 其他
Python并没有提供Switch-Case,我们可以通过字典映射实现:
def numbers_to_strings(argument):
switcher = {
0: "zero",
1: "one",
2: "two",
}
return switcher.get(argument, "nothing")
函数的字典映射
在 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()
类的调度方法
如果在一个类中,不确定要使用哪种方法,可以用一个调度方法在运行的时候来确定。
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"