最近在使用Python單元測試框架構(gòu)思自動化測試,在不段的重構(gòu)與修改中,發(fā)現(xiàn)了大量的if...else之類的語法,有沒有什么好的方式使Python具有C/C#/java等的switch功能呢?
在不斷的查找和試驗中,發(fā)現(xiàn)了這個:http://code.activestate.com/recipes/410692/,并在自己的代碼中大量的應(yīng)用,哈哈,下面來看下吧:
下面的類實現(xiàn)了我們想要的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(): # 默認(rèn)        print "something else!"
新聞熱點
疑難解答