使用上下文管理器

另一种非常易读和优雅但比 if / else 结构效率低得多的方法是构建一个类如下,它将读取并存储要与之比较的值,在上下文中将其自身暴露为可调用的如果它与存储的值匹配,则返回 true:

class Switch:
    def __init__(self, value): 
        self._val = value
    def __enter__(self):
        return self
    def __exit__(self, type, value, traceback):
        return False # Allows traceback to occur
    def __call__(self, cond, *mconds): 
        return self._val in (cond,)+mconds

然后定义案例几乎与真正的 switch / case 构造匹配(在下面的函数中公开,以便更容易炫耀):

def run_switch(value):
    with Switch(value) as case:
        if case(1):
            return 'one'
        if case(2):
            return 'two'
        if case(3):
            return 'the answer to the question about life, the universe and everything'
        # default
        raise Exception('Not a case!')

所以执行将是:

>>> run_switch(1)
one
>>> run_switch(2)
two
>>> run_switch(3)
…
Exception: Not a case!
>>> run_switch(42)
the answer to the question about life, the universe and everything

Nota Bene