Python中实现结构相似的函数调用方法
2015-03-10 11:24
721 查看
python的dict用起来很方便,可以自定义key值,并通过下标访问,示例如下:
>>> d = {'key1':'value1',
... 'key2':'value2',
... 'key3':'value3'}
>>> print d['key2']
value2
>>>
lambda表达式也是很实用的东东,示例如下:
复制代码 代码如下:
>>> f = lambda x : x**2
>>> print f(2)
4
>>>
两者结合可以实现结构相似的函数调用,使用起来很方便,示例如下:
示例一:不带参数
#! /usr/bin/python
msgCtrl = "1 : pause\n2 : stop\n3 : restart\nother to quit\n"
ctrlMap = {
'1': lambda : doPause(),
'2': lambda : doStop(),
'3': lambda : doRestart()}
def doPause():
print 'do pause'
def doStop():
print 'do stop'
def doRestart():
print 'do restart'
if __name__ == '__main__':
while True:
print msgCtrl
cmdCtrl = raw_input('Input : ')
if not ctrlMap.has_key(cmdCtrl):break
ctrlMap[cmdCtrl]()
示例二:带参数
复制代码 代码如下:#! /usr/bin/python
msgCtrl = "1 : +\n2 : -\n3 : *\nother to quit\n"
ctrlMap = {
'1': lambda x,y : x+y,
'2': lambda x,y : x-y,
'3': lambda x,y : x*y}
if __name__ == '__main__':
while True:
print msgCtrl
cmdCtrl = raw_input('Input : ')
if not ctrlMap.has_key(cmdCtrl):break
print ctrlMap[cmdCtrl](10,2),"\n"
您可能感兴趣的文章:
相关文章推荐
- Python中实现结构相似的函数调用方法
- 【廖雪峰 python教程 课后题 切片】利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:
- 【廖雪峰 python教程 课后题 切片】利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:
- Python实现调用另一个路径下py文件中的函数方法总结
- Python实现远程调用MetaSploit的方法
- python利用字典保存配置实现动态调用模块类方法
- Python使用函数默认值实现函数静态变量的方法
- 使用IDispatch::Invoke函数在C++中调用C#实现的托管类库方法
- 转:使用IDispatch::Invoke函数在C++中调用C#实现的托管类库方法
- paip.函数方法回调机制跟java php python c++的实现
- Python实现动态添加类的属性或成员函数的解决方法
- python中getattr函数使用方法 getattr实现工厂模式
- Python实现远程调用MetaSploit的方法
- Boost Python 实现C调用python错误解决方法
- paip.函数方法回调机制跟java php python c++的实现
- 用多线程方法实现在MFC/WIN32中调用OpenGL函数并创建OpenGL窗口
- Python实现动态添加类的属性或成员函数的解决方法
- 使用IDispatch::Invoke函数在C++中调用C#实现的托管类库方法
- 利用swig实现python调用C/C++的方法
- C语言MD5加密算法的简单调用实现(另附:Java/Python/Shell/Golang方法)