最近在使用Python单元测试框架构思自动化测试,在不段的重构与修改中,发现了大量的if...else之类的语法,有没有什么好的方式使Python具有C/C#/java等的switch功能呢?
在不断的查找和试验中,发现了这个:http://code.activestate.com/recipes/410692/,并在自己的代码中大量的应用,哈哈,下面来看下吧:
下面的类实现了我们想要的switch。
classswitch(object):def__init__(self,value):self.value=valueself.fall=Falsedef__iter__(self):"""Return the match method once, then stop"""yieldself.matchraiseStopIterationdefmatch(self,*args):"""Indicate whether or not to enter a case suite"""ifself.fallornotargs:returnTrueelifself.valueinargs:# changed for v1.5, see belowself.fall=TruereturnTrueelse:returnFalse下面是它的使用方法:v='ten'forcaseinswitch(v):ifcase('one'):PRint1
breakifcase('two'):print2
breakifcase('ten'):print10
breakifcase('eleven'):print11
breakifcase():# 默认print"something else!"