Python Switch Case三种实现方法代码实例


Posted in Python onJune 18, 2020

Python没有switch语句,只能通过模拟来对应实现:

方法一:使用dictionary

**values = {
value1: do_some_stuff1,
value2: do_some_stuff2,
...
valueN: do_some_stuffN,
}
values.get(var, do_default_stuff)()

根据需求可以自行更改参数内容,灵活运用

def add(x,y): 
  print x+y 
def minus(x,y): 
  print x-y 
def multiply(x,y): 
  print x*y 
def div(x,y): 
  print x/y 
def fun_case_list(key,arg1,arg2):
  operator = {
  '+':add,
  '-':minus,
  '*':multiply,
  '/':div
  }
  if operator.has_key(key):
    return operator.get(key)(arg1,arg2)
  else:
    return 'No [%s] case in dic'%key #or do other func
if __name__ == "__main__":
  fun_case_list('*',3,5)
  fun_case_list('l',3,4)

或者你可以自己造一个类来实现:

class switch_case(object):
  def case_to_function(self,case,arg1,arg2):
    func_name = 'case_func_'+str(case)
    try:
      method = getattr(self,func_name)
      return method(arg1,arg2)
    except AttributeError:
      return 'No func found in case list,do default action here'
  def case_func_add(self,arg1,arg2):
    temp = arg1 + arg2
    return temp
  def case_func_minus(self,arg1,arg2):
    temp = arg1 - arg2
    return temp
  def case_func_multiply(self,arg1,arg2):
    temp = arg1 * arg2
    return temp
  def case_func_div(self,arg1,arg2):
    temp = arg1 / arg2
    return temp
func = 'minus'
case = switch_case()
print case.case_to_function(func,2,5)


#或者是构造属性去送参数,看个人喜好
class switch_case(object):
  def __init__(self, case, arg1, arg2):
    self.case = str(case)
    self.arg1 = arg1
    self.arg2 = arg2
  def case_to_function(self):
    func_name = 'case_func_'+str(self.case)
    try:
      method = getattr(self,func_name)
      return method()
    except AttributeError:
      return 'No func found in case list,do default action here'
    
  def case_func_add(self):
    temp = self.arg1 + self.arg2
    return temp
  def case_func_minus(self):
    temp = self.arg1 - self.arg2
    return temp
  def case_func_multiply(self):
    temp = self.arg1 * self.arg2
    return temp
  def case_func_div(self):
    temp = self.arg1 / self.arg2
    return temp

func = 'minxus'
case = switch_case(func,2,5)
print case.case_to_function()

方法二:使用lambda

result = {
'a': lambda x: x * 5,
'b': lambda x: x + 7,
'c': lambda x: x - 2
}[value](x)

方法三:Brian Beck提供了一个类 switch 来实现switch的功能

class switch(object):
  def __init__(self, value):
    self.value = value
    self.fall = False
  def __iter__(self):
    """Return the match method once, then stop"""
    yield self.match
    raise StopIteration
  def match(self, *args):
    """Indicate whether or not to enter a case suite"""
    if self.fall or not args:
      return True
    elif self.value in args: # changed for v1.5, see below
      self.fall = True
      return True
    else:
      return False

v = 'two'
for case in switch(v):
  if case('one'):
    print 1
    break
  if case('two'):
    print 2
    break
  if case('ten'):
    print 10
    break
  if case('eleven'):
    print 11
    break
  if case(): # default, could also just omit condition or 'if True'
    print "something else!"
    # No need to break here, it'll stop anyway

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
学习python的几条建议分享
Feb 10 Python
浅谈Python中数据解析
May 05 Python
python3中dict(字典)的使用方法示例
Mar 22 Python
python爬虫入门教程--HTML文本的解析库BeautifulSoup(四)
May 25 Python
JS设计模式之责任链模式实例详解
Feb 03 Python
对python实现二维函数高次拟合的示例详解
Dec 29 Python
Python实现爬取亚马逊数据并打印出Excel文件操作示例
May 16 Python
Django后台admin的使用详解
Jul 08 Python
python打造爬虫代理池过程解析
Aug 15 Python
对python中UDP,socket的使用详解
Aug 22 Python
Pyqt助手安装PyQt5帮助文档过程图解
Nov 20 Python
filter使用python3代码进行迭代元素的实例详解
Dec 03 Python
Python3开发环境搭建详细教程
Jun 18 #Python
Python collections.defaultdict模块用法详解
Jun 18 #Python
python实现批量命名照片
Jun 18 #Python
pandas之分组groupby()的使用整理与总结
Jun 18 #Python
解决Keyerror ''acc'' KeyError: ''val_acc''问题
Jun 18 #Python
Python调用shell cmd方法代码示例解析
Jun 18 #Python
Python如何自动获取目标网站最新通知
Jun 18 #Python
You might like
追求程序速度,而不是编程的速度
2008/04/23 PHP
浅谈PHP无限极分类原理
2019/03/14 PHP
PHP单元测试配置与使用方法详解
2019/12/27 PHP
解决Extjs上传图片无法预览的解决方法
2012/03/22 Javascript
自己动手实现jQuery Callbacks完整功能代码详解
2013/11/25 Javascript
js window对象属性和方法相关资料整理
2015/11/11 Javascript
基于jquery实现左右按钮点击的图片切换效果
2021/01/27 Javascript
JavaScript数据结构与算法之栈与队列
2016/01/29 Javascript
JS通过Cookie判断页面是否为首次打开
2016/02/05 Javascript
JavaScript 正则表达式中global模式的特性
2016/02/25 Javascript
js提交form表单,并传递参数的实现方法
2016/05/25 Javascript
Bootstrap布局之栅格系统学习笔记
2017/05/04 Javascript
解决webpack -p压缩打包react报语法错误的方法
2017/07/03 Javascript
Vue.js中的图片引用路径的方式
2017/07/28 Javascript
微信小程序 MinUI组件库系列之badge徽章组件示例
2018/08/20 Javascript
Bootstrap4 gulp 配置详解
2019/01/06 Javascript
基于JS开发微信网页录音功能的实例代码
2019/04/30 Javascript
详解js实时获取并显示当前时间的方法
2019/05/10 Javascript
jquery实现Ajax请求的几种常见方式总结
2019/05/28 jQuery
小程序中canvas的drawImage方法参数使用详解
2019/07/04 Javascript
解决layui批量传值到后台操作时出现传值为空的问题
2019/09/28 Javascript
vue 自定义右键样式的实例代码
2019/11/06 Javascript
Vue 中使用 typescript的方法详解
2020/02/17 Javascript
基于ajax及jQuery实现局部刷新过程解析
2020/09/12 jQuery
Python代码缩进和测试模块示例详解
2018/05/07 Python
使用pycharm生成代码模板的实例
2018/05/23 Python
python 实现敏感词过滤的方法
2019/01/21 Python
一款html5 canvas实现的图片玻璃碎片特效
2014/09/11 HTML / CSS
HTML5 HTMLCollection和NodeList的区别详解
2020/04/29 HTML / CSS
Love, Bonito国际官网:新加坡女装品牌
2021/03/13 全球购物
写一个用矩形法求定积分的通用函数
2012/11/08 面试题
水利学院求职自荐书
2014/02/01 职场文书
毕业设计说明书
2014/05/07 职场文书
领导班子整改方案和个人整改措施
2014/10/25 职场文书
2014年接待工作总结
2014/11/26 职场文书
PHP中国际化的字符串排序和比较对象详解
2021/08/23 PHP