Python Tricks(十九)—— switch 的实现

python 原生语法不支持 switch,体现了 Python 大道至简的设计思路,有时为了避免啰嗦的 if elif等判断语句,我们可以用字典来代替 switch 的各分支,也即建立表达式和操作的映射。

def add(x, y):
    return x + y
def sub(x, y):
    return x - y
def mul(x, y):
    return x*y
def div(x, y):
    return float(x)/y

def calc(x, o, y):
    return operators[o](x, y)
            # 与 operators.get(o)(x, y) 相比会抛出异常

operators = {'+': add, '-': sub, '*': mul, '/': div}

当然我们可以进一步利用 Python 强大的库:

from operator import add, sub, mul, div
operators = {'+': add, '-': sub, '*': mul, '/': div}

python中switch语句用法

原文地址:https://www.cnblogs.com/mtcnn/p/9424311.html