我已阅读 Replacements for switch statement in Python?似乎没有一个答案能完全模拟开关。
我知道您可以使用 if elif else
或字典,但我想知道...是否有可能在 Python 中完全模拟一个开关,包括 fall-through 和 default(无需定义巨大的预先功能)?
我并不过分关注性能,主要对可读性感兴趣,并希望获得 switch 语句的逻辑布局,就像 Python 中的类 C 语言一样
这是否可以实现?
因为您不想使用字典或 if elif else,所以最接近的可能仿真 AFAIK 应该是这样的:
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
import string
c = 'A'
for case in switch(c):
if case(*string.lowercase): # note the * for unpacking as arguments
print "c is lowercase!"
break
if case(*string.uppercase):
print "c is uppercase!"
break
if case('!', '?', '.'): # normal argument passing style also applies
print "c is a sentence terminator!"
break
if case(): # default
print "I dunno what c was!"
@作者布赖恩·贝克
@来源:http://code.activestate.com/recipes/410692/ <- 那里还有其他建议,您可能想查看是否有足够好的建议。
请注意,您将必须使用(或导入此类开关)
我是一名优秀的程序员,十分优秀!