新闻动态

Python实现switch/case语句

发布日期:2022-02-14 12:41 | 文章来源:CSDN

使用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

总结

就个人来说,使用字典来实现switch/case是最为灵活的,但是理解上也有一定的难度。

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注本站的更多内容!

国外服务器租用

版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。

相关文章

实时开通

自选配置、实时开通

免备案

全球线路精选!

全天候客户服务

7x24全年不间断在线

专属顾问服务

1对1客户咨询顾问

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部