gpt4 book ai didi

python - 在 Python 中模拟全功能开关

转载 作者:太空宇宙 更新时间:2023-11-04 03:46:29 26 4
gpt4 key购买 nike

我已阅读 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/ <- 那里还有其他建议,您可能想查看是否有足够好的建议

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

关于python - 在 Python 中模拟全功能开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23546864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com