方案一
参考链接
https://www.cnblogs.com/dbf-/p/10601216.html
如果只是简单使用,那这里方案一的方法更简明一些。
def case1(): # 第一种情况执行的函数
print('This is the case1')
def case2(): # 第二种情况执行的函数
print('This is the case2')
def case3(): # 第三种情况执行的函数
print('This is the case3')
def default(): # 默认情况下执行的函数
print('No such case')
switch = {'case1': case1, # 注意此处不要加括号
'case2': case2,
'case3': case3,
}
choice = 'case1' # 获取选择
switch.get(choice, default)() # 执行对应的函数,如果没有就执行默认的函数
方案二
参考链接
https://blog.csdn.net/l460133921/article/details/74892476
这篇文章中还有把 switch 写成类
def success(msg):
print msg
def debug(msg):
print msg
def error(msg):
print msg
def warning(msg):
print msg
def other(msg):
print msg
def notify_result(num, msg):
numbers = {
0 : success,
1 : debug,
2 : warning,
3 : error
}
method = numbers.get(num, other)
if method:
method(msg)
if __name__ == "__main__":
notify_result(0, "success")
notify_result(1, "debug")
notify_result(2, "warning")
notify_result(3, "error")
notify_result(4, "other")