首页 > 学院 > 开发设计 > 正文

Python实现类似switch...case功能

2019-11-14 17:23:24
字体:
来源:转载
供稿:网友

最近在使用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!"

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表