我找到了一个实现 switch 语句的函数 -->
File = open('/file.txt','r')
String = File.readline()
String = str(String)
print String
for case in switch(String):
if case("Head"):
print "test successed"
break
if case("Small"):
print String
break
if case("Big"):
print String
break
if case():
print String
break
我打印它时的字符串值是 Head,但 switch 语句总是转到最后一种情况.. 该函数显然工作正常,因为当我用 v =“Head”更改字符串时它工作了!!!
知道出了什么问题吗?
开关功能 -->
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