Python实现相仿switch.case功能
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!"
- 1楼瘸腿狼
- python中难道没有替代case的方法吗?
- Re: ListenWind
- @瘸腿狼,Python中只有使用if...elif...else来实现分支,如果想使用case的话,可以采用文中的方式,当然了,还有其他的方式实现case,只不过我认为这个方式是最好理解和使用的。