python --闭包学习
2016-01-25 09:45
597 查看
闭包概念:
Closure:内部函数中对enclosing作用域的变量进行引用
enclosing作用域:函数内部与内嵌函之间
范例1:
输出:
passline is 60
89 is pass
passline is 90
89 is failed
范例2:
输出:
('in_dec arg=', (1, 2, 3, 4, 5))
15
('in_dec arg=', (1, 2, 3, 4, 5, '6'))
0
('in_dec arg=', (1, 2, 3, 4, 5))
3
('in_dec arg=', ())
0
闭包作用
1:封装
2:代码复用
Closure:内部函数中对enclosing作用域的变量进行引用
enclosing作用域:函数内部与内嵌函之间
范例1:
#coding:utf-8 def set_passline(passline): def cmp(val): if val>= passline: print "passline is %d"%passline print "%d is pass"%val else: print "passline is %d"%passline print "%d is failed"%val return cmp f_100=set_passline(60) f_150=set_passline(90) f_100(89) f_150(89)
输出:
passline is 60
89 is pass
passline is 90
89 is failed
范例2:
#coding:utf-8 def my_sum(*arg): return sum(arg) def my_average(*arg): return sum(arg)/len(arg) def dec(func): def in_dec(*arg): print ('in_dec arg=',arg) if len(arg)==0: return 0 for val in arg: if not isinstance(val,int): return 0 return func(*arg) return in_dec my_sum=dec(my_sum) my_average=dec(my_average) print my_sum(1,2,3,4,5) print my_sum(1,2,3,4,5,'6') print my_average(1,2,3,4,5) print my_average()
输出:
('in_dec arg=', (1, 2, 3, 4, 5))
15
('in_dec arg=', (1, 2, 3, 4, 5, '6'))
0
('in_dec arg=', (1, 2, 3, 4, 5))
3
('in_dec arg=', ())
0
闭包作用
1:封装
2:代码复用
相关文章推荐
- 使SourceInsight支持Python语言的方法
- python废话二:学习python2还是python3
- 21行Python代码实现拼写检查器
- Python--(高阶)函数
- Python Unit Testing
- Python Unit Testing
- 44. Wildcard Matching leetcode Python 2016 new season
- 43. Multiply Strings leetcode python 2016 new season
- Python常用函数
- Python如何进行cross validation training
- Python/Keras如何将给定的数据集打乱
- Python-装饰器以及对带有参数的装饰器的理解
- Python 删除列表中的重复数据
- 21行Python代码实现拼写检查器
- 基于Python Shell获取hostname和fqdn释疑
- 谈谈Python进行验证码识别的一些想法
- Python网站验证码识别
- 详解Python验证码识别
- Python开发如何在ubuntu 15.10 上配置vim
- Python编程中对文件和存储器的读写示例