【问题标题】:Emulate a full-featured switch in Python在 Python 中模拟全功能开关
【发布时间】:2014-05-08 16:01:49
【问题描述】:

我已阅读 Replacements for switch statement in Python?,但似乎没有一个答案完全模拟开关。

我知道你可以使用if elif else 或字典,但我想知道......是否可以在 Python 中完全模拟一个开关,包括贯穿和默认的开关(无需事先定义一个巨大的函数)?

我并不太关心性能,主要对可读性感兴趣,并希望获得 switch 语句的逻辑布局,就像 Python 中的类 C 语言一样

这是否可以实现?

【问题讨论】:

  • 请问为什么你要这样做?一般来说,在 Python 中有更好的处理方法,这就是为什么 switch 语句不是语言的一部分......
  • @JonCage 我问purley是出于好奇,但为了争论;想象一下,您有想要转换为 python 的 c 代码(无论出于何种原因),它包含一个 switch 使用 fallthrough 和 default 的语句。
  • @g.d.d.c 你不会失败
  • 这个问题似乎是题外话,因为它似乎无法回答。 OP 链接了几个资源,说明没有什么完全像他想要做的那样,然后询问如何完全做到这一点。
  • @nettux443 共识似乎是否定的,但我认为将问题关闭到可能的答案有点激烈。

标签: python switch-statement


【解决方案1】:

由于您不想使用字典或 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!"

@作者布莱恩·贝克

@source: http://code.activestate.com/recipes/410692/ 是否适合您。

请注意,您必须使用(或导入此类开关)

【讨论】:

  • 我在 +1 的独创性和 -1 的恐怖之间左右为难。
  • 此解决方案是否允许像 case('.'): 'do something' case('!','?'): 'do something else' break 中的那样掉线?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
  • 2012-10-11
相关资源
最近更新 更多