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实现每次处理一个字符的三种方法
Oct 09 Python
python3连接MySQL数据库实例详解
May 24 Python
vue.js实现输入框输入值内容实时响应变化示例
Jul 07 Python
Django中多种重定向方法使用详解
Jul 17 Python
python3中替换python2中cmp函数的实现
Aug 20 Python
Django Admin中增加导出CSV功能过程解析
Sep 04 Python
python os.path.isfile()因参数问题判断错误的解决
Nov 29 Python
Django使用Celery加redis执行异步任务的实例内容
Feb 20 Python
python如何查看安装了的模块
Jun 23 Python
python接入支付宝的实例操作
Jul 20 Python
如何在pycharm中安装第三方包
Oct 27 Python
详解Python中string模块除去Str还剩下什么
Nov 30 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
曾在DC漫画界反派角色扮演的演员,谁才是你心目中的小丑之王?
2020/04/09 欧美动漫
snoopy 强大的PHP采集类使用实例代码
2010/12/09 PHP
PHP实现简单实用的验证码类
2015/07/29 PHP
php中关于换行的实例写法
2019/09/26 PHP
js url传值中文乱码之解决之道
2009/11/20 Javascript
js加强的经典分页实例
2013/03/15 Javascript
使用jquery hover事件实现表格的隔行换色功能示例
2013/09/03 Javascript
第一次接触神奇的Bootstrap表单
2016/07/27 Javascript
Jquery获取当前城市的天气信息
2016/08/05 Javascript
JS实现物体带缓冲的间歇运动效果示例
2016/12/22 Javascript
vue实现弹框遮罩点击其他区域弹框关闭及v-if与v-show的区别介绍
2018/09/29 Javascript
react koa rematch 如何打造一套服务端渲染架子
2019/06/26 Javascript
vuejs+element UI table表格中实现禁用部分复选框的方法
2019/09/20 Javascript
从0到1学习JavaScript编写贪吃蛇游戏
2020/07/28 Javascript
vue实现移动端触屏拖拽功能
2020/08/21 Javascript
Javascript实现单选框效果
2020/12/09 Javascript
python网络编程之UDP通信实例(含服务器端、客户端、UDP广播例子)
2014/04/25 Python
Python实现二维有序数组查找的方法
2016/04/27 Python
Python中pillow知识点学习
2018/04/30 Python
详解Python基础random模块随机数的生成
2019/03/23 Python
Python3实现定时任务的四种方式
2019/06/03 Python
利用Python模拟登录pastebin.com的实现方法
2019/07/12 Python
对python中的装包与解包实例详解
2019/08/24 Python
对Python获取屏幕截图的4种方法详解
2019/08/27 Python
python实现从wind导入数据
2019/12/03 Python
Python matplotlib绘制图形实例(包括点,曲线,注释和箭头)
2020/04/17 Python
python随机模块random的22种函数(小结)
2020/05/15 Python
Django Session和Cookie分别实现记住用户登录状态操作
2020/07/02 Python
html5使用html2canvas实现浏览器截图的示例
2017/08/31 HTML / CSS
企业厂长岗位职责
2013/12/17 职场文书
作文评语集锦大全
2014/04/23 职场文书
2014年财务工作自我评价
2014/09/23 职场文书
债务追讨授权委托书范本
2014/10/16 职场文书
物业保洁员岗位职责
2015/02/13 职场文书
Java Socket实现Redis客户端的详细说明
2021/05/26 Redis
正则表达式拆分url实例代码
2022/02/24 Java/Android