我已阅读Replacements for switch statement in Python?并且没有一个答案似乎完全模拟了开关。
我知道你可以使用 if elif else
或字典,但我想知道......在Python中是否可以完全模拟一个开关,包括失败和默认(无需定义一个巨大的)预先函数)?
我并不太关心性能,主要对可读性感兴趣,并且希望获得 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/ <- 还有其他建议,您可能需要检查是否有任何适合您。
请注意,您必须使用(或导入此类开关)
关于python - 在 Python 中模拟全功能交换机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23546864/