在Python中模拟一个功能完备的开关

2 投票
1 回答
877 浏览
提问于 2025-04-18 05:51

我看过一篇关于在Python中替代switch语句的文章,里面的回答似乎都没有完全模拟出switch的功能。

我知道可以用if elif else或者字典来实现,但我在想……在Python中有没有办法完全模拟一个switch语句,包括可以“掉落”的情况和默认值(而不需要事先定义一个很大的函数)?

我对性能不是特别在意,主要是想要代码的可读性,想在Python中得到类似于C语言那样的switch语句的逻辑布局。

这能实现吗?

1 个回答

2

如果你不想使用字典或者 if elif else 这种方式,那么我知道的最接近的替代方法可能是这样的:

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!"

@作者 Brian Beck

@来源: http://code.activestate.com/recipes/410692/ <- 这里还有其他建议,你可以去看看是否有哪个适合你

注意,你需要使用(或者导入这个类 switch)

撰写回答