Closure concept:
Closure: References to variables in enclosing scope in intrinsic functions
Enclosing scope: between function interior and embedded letter
Example 1:
#Coding:utf-8defSet_passline (passline):defCMP (val):ifval>=Passline:Print "Passline is%d"%PasslinePrint "%d is pass"%ValElse: Print "Passline is%d"%PasslinePrint "%d is failed"%Valreturncmpf_100=set_passline (60) f_150=set_passline (90) f_100 (89) f_150 (89)
Output:
Passline is 60
The IS pass
Passline is 90
Failed
Example 2:
#Coding:utf-8defMy_sum (*Arg):returnsum (ARG)defMy_average (*Arg):returnSUM (ARG)/Len (ARG)defDec (func):defIn_dec (*Arg):Print('In_dec arg=', Arg)ifLen (arg) = =0:return0 forValinchARG:if notisinstance (val,int):return0returnFunc (*Arg)returnIn_decmy_sum=Dec (my_sum) My_average=Dec (my_average)PrintMy_sum (1,2,3,4,5)PrintMy_sum (1,2,3,4,5,'6')PrintMy_average (1,2,3,4,5)PrintMy_average ()
Output:
(' 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
Closure function
1: Package
2: Code Reuse
Python--Closure learning