python利用dict模拟switch

时间:2022-03-01 09:38:05

pytho本身并未提供switch语句,但可以通过dict来模拟switch,

#方法1
def add(x,y):
return x+y def dec(x,y):
return x-y def multi(x,y):
return x*y def div(x,y):
return x/y operater = {'+':add,'-':dec,'*':multi,'/':div}
def calculator(x,o,y):
return operater.get(o)(x,y) #方法2
def calculator1(x,o,y):
return {'+':x+y,'-':x-y,'*':x*y,'/':x/y}.get(o) def test():
print calculator(2, '*', 6)
print calculator1(2,'+',6)
if __name__ == "__main__":
test()

方法二每次调用时都需要生成dict。