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 11 Python
Python中的with...as用法介绍
May 28 Python
Python 专题三 字符串的基础知识
Mar 19 Python
Python实现基于C/S架构的聊天室功能详解
Jul 07 Python
Python爬虫框架scrapy实现downloader_middleware设置proxy代理功能示例
Aug 04 Python
对Xpath 获取子标签下所有文本的方法详解
Jan 02 Python
pandas把所有大于0的数设置为1的方法
Jan 26 Python
使用python PIL库实现简单验证码的去噪方法步骤
May 10 Python
python 日期排序的实例代码
Jul 11 Python
Python获取命令实时输出-原样彩色输出并返回输出结果的示例
Jul 11 Python
django的csrf实现过程详解
Jul 26 Python
pandas中对文本类型数据的处理小结
Nov 01 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
Php中文件下载功能实现超详细流程分析
2012/06/13 PHP
PHP可变函数的使用详解
2013/06/14 PHP
编写PHP脚本使WordPress的主题支持Widget侧边栏
2015/12/14 PHP
json-lib出现There is a cycle in the hierarchy解决办法
2010/02/24 Javascript
Json对象替换字符串占位符实现代码
2010/11/17 Javascript
JavaScript去掉数组中的重复元素
2011/01/13 Javascript
解读JavaScript代码 var ie = !-[1,] 最短的IE判定代码
2011/05/28 Javascript
JavaScript中的Math.atan2()方法使用详解
2015/06/15 Javascript
JS与jQuery遍历Table所有单元格内容的方法
2015/12/07 Javascript
AngularJS Module方法详解
2015/12/08 Javascript
TypeScript Type Innference(类型判断)
2016/03/10 Javascript
Bootstrap3.0学习教程之JS折叠插件
2016/05/27 Javascript
全面接触神奇的Bootstrap导航条实战篇
2016/08/01 Javascript
利用JQuery实现datatables插件的增加和删除行功能
2017/01/06 Javascript
详解Angular4 路由设置相关
2017/08/26 Javascript
通过nodejs 服务器读取HTML文件渲染到页面的方法
2018/05/17 NodeJs
Bootstrap-table自定义可编辑每页显示记录数
2018/09/07 Javascript
node.js使用redis储存session的方法
2018/09/26 Javascript
koa2使用ejs和nunjucks作为模板引擎的使用
2018/11/27 Javascript
迅速了解一下ES10中Object.fromEntries的用法使用
2019/03/05 Javascript
vue实现可视化可拖放的自定义表单的示例代码
2019/03/20 Javascript
vue cli3 调用百度翻译API翻译页面的实现示例
2019/09/13 Javascript
解决vue scoped html样式无效的问题
2020/10/24 Javascript
Python交换变量
2008/09/06 Python
在Python的循环体中使用else语句的方法
2015/03/30 Python
python实现最大优先队列
2019/08/29 Python
Django之使用内置函数和celery发邮件的方法示例
2019/09/16 Python
Django 404、500页面全局配置知识点详解
2020/03/10 Python
htnl5利用svg页面高斯模糊的方法
2018/07/20 HTML / CSS
到底Java是如何传递参数的?是by value或by reference?
2012/07/13 面试题
拒绝黄毒毒宣传标语
2014/06/26 职场文书
群众路线教育实践活动的心得体会
2014/09/03 职场文书
2015年毕业生自我鉴定模板
2014/09/19 职场文书
小学生红领巾广播稿
2015/08/19 职场文书
基于Java的MathML转图片的方法(示例代码)
2021/06/23 Java/Android
Python简易开发之制作计算器
2022/04/28 Python