python中实现witch case
方案一
参考链接
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)() # 执行对应的函数,如果没有就执行默认的函数
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
方案二
参考链接
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")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
推荐阅读