闭包概念:
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:代码复用
时间: 2024-10-19 16:58:54