使用上下文管理器

另一種非常易讀和優雅但比 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