【发布时间】:2012-05-07 06:07:52
【问题描述】:
我找到了一个实现 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
【问题讨论】:
-
你应该链接
case和switch对象/函数的实现,否则你在问一个没人能回答的问题。 -
你把这个
switch函数放在哪里了?你能指出它的来源吗? -
我添加了函数的实现
-
你为什么要这样做?您正在生成完全非pythonic的代码。满足于
if string == 'Head':、elif string == 'Small':等。 -
@ChrisMorgan - 更好的是使用字典:P
标签: python file-io switch-statement