zoukankan      html  css  js  c++  java
  • Python实现类似switch...case功能

    最近在使用Python单元测试框架构思自动化测试,在不段的重构与修改中,发现了大量的if...else之类的语法,有没有什么好的方式使Python具有C/C#/JAVA等的switch功能呢?

    在不断的查找和试验中,发现了这个:http://code.activestate.com/recipes/410692/,并在自己的代码中大量的应用,哈哈,下面来看下吧:

    下面的类实现了我们想要的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 = 'ten' 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(): # 默认 print "something else!"
  • 相关阅读:
    xml在html中的使用
    getElementsByTagName的用法
    opener 的使用
    动态增加属性
    innerText, innerHTML,outerHTML
    button的css属性
    动态改变select中option的次序
    input 的样式
    zkw线段树
    接着吐槽(2012/5/23)
  • 原文地址:https://www.cnblogs.com/ListenWind/p/4267517.html
Copyright © 2011-2022 走看看