Skip to content Skip to main navigation Skip to footer

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!"
 

来源:http://www.cnblogs.com/ListenWind/p/4267517.html

0 Comments

There are no comments yet

Leave a comment

Your email address will not be published.