Python实现switch/case语句
作者:liulijun-dev 时间:2021-03-30 00:46:28
使用if…elif…elif…else 实现switch/case
可以使用if…elif…elif..else序列来代替switch/case语句,这是大家最容易想到的办法。但是随着分支的增多和修改的频繁,这种代替方式并不很好调试和维护。
使用字典 实现switch/case
可以使用字典实现switch/case这种方式易维护,同时也能够减少代码量。如下是使用字典模拟的switch/case实现:
def num_to_string(num):
numbers = {
0 : "zero",
1 : "one",
2 : "two",
3 : "three"
}
return numbers.get(num, None)
if __name__ == "__main__":
print num_to_string(2)
print num_to_string(5)
执行结果如下:
two
None
Python字典中还可以包括函数或Lambda表达式,代码如下:
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")
执行结果如下:
success
debug warning error
other
通过如上示例可以证明能够通过Python字典来完全实现switch/case语句,而且足够灵活。尤其在运行时可以很方便的在字典中添加或删除一个switch/case选项。
在类中可使用调度方法实现switch/case
如果在一个类中,不确定要使用哪种方法,可以用一个调度方法在运行的时候来确定。代码如下:
class switch_case(object):
def case_to_function(self, case):
fun_name = "case_fun_" + str(case)
method = getattr(self, fun_name, self.case_fun_other)
return method
def case_fun_1(self, msg):
print msg
def case_fun_2(self, msg):
print msg
def case_fun_other(self, msg):
print msg
if __name__ == "__main__":
cls = switch_case()
cls.case_to_function(1)("case_fun_1")
cls.case_to_function(2)("case_fun_2")
cls.case_to_function(3)("case_fun_other")
执行结果如下:
case_fun_1
case_fun_2
case_fun_other
来源:https://blog.csdn.net/l460133921/article/details/74892476
标签:Python,switch,case
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python的一些用法分享
2021-04-19 20:49:22
Python3.7实现中控考勤机自动连接
2022-08-07 16:24:22
在Python的Django框架中包装视图函数
2021-01-08 03:45:45
python使用numpy读取、保存txt数据的实例
2021-04-05 22:38:49
![](https://img.aspxhome.com/file/2023/0/72950_0s.jpg)
python函数指定默认值的实例讲解
2021-07-20 14:05:01
6个卓越Web设计细节
2010-03-29 12:56:00
![](https://img.aspxhome.com/file/UploadPic/20103/29/01-23s.jpg)
python实现定时压缩指定文件夹发送邮件
2022-06-02 19:32:36
使用AJAX和Django获取数据的方法实例
2021-11-14 20:40:20
秒杀场景的缓存、队列、锁使用Redis优化设计方案
2023-05-29 19:07:18
![](https://img.aspxhome.com/file/2023/9/55339_0s.png)
Python OS模块常用函数说明
2022-08-28 06:34:39
用python修改excel表某一列内容的操作方法
2022-01-22 20:51:29
![](https://img.aspxhome.com/file/2023/0/97590_0s.png)
Python基础教程之名称空间以及作用域
2022-08-10 07:51:47
使用游标进行PHP SQLSRV查询的方法与注意事项
2023-05-22 10:51:10
浅谈uniapp页面跳转的解决方案
2023-08-23 01:45:51
![](https://img.aspxhome.com/file/2023/3/56133_0s.jpg)
Python获取时间的操作示例详解
2023-05-21 07:54:56
![](https://img.aspxhome.com/file/2023/7/109637_0s.png)
Python爬虫框架Scrapy常用命令总结
2022-02-21 20:45:23
![](https://img.aspxhome.com/file/2023/3/118293_0s.png)
在ASP中使用类,实现模块化
2008-10-15 14:57:00
对pandas中iloc,loc取数据差别及按条件取值的方法详解
2021-06-15 01:58:05
python实现读取并显示图片的两种方法
2023-12-20 12:51:14
Python入门篇之面向对象
2023-10-19 16:31:51