python 中并没有switch语句,但是有一个数据类型与switch语句特别相似,它就是 dict{ key: value, ...}
下面用 dict{ key:value,..} 来简单的实现switch语句:
#!/usr/bin/env python #coding:utf-8 from __future__ import division __version__ = 1.0 def jia(x, y, *args, **kwargs): return x + y def jian(x, y, *args, **kwargs): return x - y def cheng(x, y, *args, **kwargs): return x * y def chu(x, y, *args, **kwargs): return x / y operator = {"+":jia, "-":jian, "*":cheng, "/":chu} #核心 def fun(o, x, y): print operator.get(o)(x, y) fun("+",3, 6)
时间: 2024-12-12 13:53:35