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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM