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的web.py框架下的application.py模块
May 02 Python
python实现的简单窗口倒计时界面实例
May 05 Python
使用Python的Twisted框架编写非阻塞程序的代码示例
May 25 Python
浅析Python中return和finally共同挖的坑
Aug 18 Python
Python多线程原理与用法详解
Aug 20 Python
在Python中定义一个常量的方法
Nov 10 Python
详解python列表生成式和列表生成式器区别
Mar 27 Python
如何在Django配置文件里配置session链接
Aug 06 Python
浅谈Python2之汉字编码为unicode的问题(即类似\xc3\xa4)
Aug 12 Python
Python实现ElGamal加密算法的示例代码
Jun 19 Python
基于tensorflow __init__、build 和call的使用小结
Feb 26 Python
Python基础之操作MySQL数据库
May 06 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
乱谈我对耳机、音箱的感受
2021/03/02 无线电
phpmyadmin导入(import)文件限制的解决办法
2009/12/11 PHP
PHP使用array_fill定义多维数组的方法
2015/03/18 PHP
PHP微信开发之二维码生成类
2015/06/26 PHP
符合W3C网页标准的iframe标签的使用方法
2007/07/19 Javascript
用AJAX返回HTML片段中的JavaScript脚本
2010/01/04 Javascript
IE下写xml文件的两种方式(fso/saveAs)
2013/08/05 Javascript
textarea焦点的用法实现获取焦点清空失去焦点提示效果
2014/05/19 Javascript
JavaScript事件委托技术实例分析
2015/02/06 Javascript
javascript动态生成树形菜单的方法
2015/11/14 Javascript
jQuery xml字符串的解析、读取及查找方法
2016/03/01 Javascript
解决Vue2.0自带浏览器里无法打开的原因(兼容处理)
2017/07/28 Javascript
JS动画定时器知识总结
2018/03/23 Javascript
浅谈Angular6的服务和依赖注入
2018/06/27 Javascript
element ui table 增加筛选的方法示例
2018/11/02 Javascript
微信jssdk逻辑在vue中的运用详解
2018/11/14 Javascript
Vue v-bind动态绑定class实例方法
2020/01/15 Javascript
在Python的gevent框架下执行异步的Solr查询的教程
2015/04/16 Python
python基于phantomjs实现导入图片
2016/05/13 Python
从源码解析Python的Flask框架中request对象的用法
2016/06/02 Python
python不换行之end=与逗号的意思及用途
2017/11/21 Python
Python获取当前函数名称方法实例分享
2018/01/18 Python
python实现人民币大写转换
2018/06/20 Python
对python中url参数编码与解码的实例详解
2019/07/25 Python
Python一键安装全部依赖包的方法
2019/08/12 Python
Python如何把多个PDF文件合并代码实例
2020/02/13 Python
python实现打砖块游戏
2020/02/25 Python
Python如何使用paramiko模块连接linux
2020/03/18 Python
python实现交并比IOU教程
2020/04/16 Python
英国婴儿产品专家:Samuel Johnston
2020/04/20 全球购物
仓库门卫岗位职责
2013/12/22 职场文书
语文教学随笔感言
2014/02/18 职场文书
养牛场项目建议书
2014/05/13 职场文书
国庆节活动总结
2014/08/26 职场文书
小学红领巾广播稿(3篇)
2014/09/13 职场文书
2015年暑期见闻
2015/07/14 职场文书