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

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航