python - 在 Python 中模拟全功能交换机

标签 python switch-statement

我已阅读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/

相关文章:

python - Scrapy:将参数传递给 cmdline.execute()

JavaScript/jQuery : possible to 'automate' switch statement through for loop?

ios - 快速组合枚举

python - 计算对 ChatGPT 的 API 请求(包括函数)的总 token

python - Django Rest Framework,使用MultiPartParser时Query Dict为空

python - 如何匹配 python 正则表达式中的不可打印字符?

python - 将参数传递给具有命名参数的函数

ios - 根据模式/大小写更改 navigationBar.title?

typescript - 如何使用 Typescript 在 Redux reducer 函数内实现详尽的 switch 语句?如何处理 Redux 的内部 @@redux 操作

c++ - 我怎样才能告诉 gcc 在不中断的情况下对 switch/case 语句发出警告(或失败)?