python利用dict模拟switch
2016-03-02 14:33
357 查看
pytho本身并未提供switch语句,但可以通过dict来模拟switch,
方法二每次调用时都需要生成dict。
#方法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。
相关文章推荐
- python之全局变量的测试
- python socket编程详细介绍
- 在命令行中执行python,提示提示No module named "xxx"
- python全局变量
- python shelve模块
- 随手收藏,python中的各种类型转换
- 用python api管理vcenter
- python __file__ 与argv[0]
- Python - 批量改变文件名
- python with的用法
- python中yield用法
- python 面向对象高级编程
- python错误、调试和测试
- Tkinter控件使用image的问题
- 分析Python中设计模式之Decorator装饰器模式的要点
- 【python】scrapy安装
- python 500 lines or less 参考地址
- python的资料
- 实例解析Python设计模式编程之桥接模式的运用
- python3 bytes、str的区别