1.1 return function1.1.1 function as return value
>>> def lazy_sum (*args): # variable parameter
... def sum ():
... Ax = 0
... for i in args: # calling parameters of an external function
.... Ax = ax + I
.... return ax
... return sum-- a function returned here
...
>>>
>>>
>>> lazy_sum (1, 3, 5, 7)
<function Lazy_sum.<locals>.sum at0x2b8091d87268>
>>> lazy_sum (1,3, 5, 7) ()
16
>>> F =lazy_sum (1, 3, 5, 7)
>>> F
<function Lazy_sum.<locals>.sum at0x2b8091d87268>
>>> F ()
16
Note: When we call lazy_sum () , each call will return a new function , even if the same parameters are passed in
>>> f1 = lazy_sum (1, 3, 5, 7, 9)
>>> F2 = lazy_sum (1, 3, 5, 7, 9)
>>> F1 = = F2
False
1.1.2 Closed Package
Look at the closure problem.
>>> def count ():
... fs = []
... for i in range (1, 4):
... def f ():
... return I*i
... fs.append (f)
... return FS
...
>>> F1, F2, F3 = count ()-- variable i all refer to 3
>>>
>>> F1
<function COUNT.<LOCALS>.F at0x2b8091d87488>
>>> F1 ()
9
>>> F2 ()
9
>>> F3 ()
9
the back function references the variable i, but it is not executed immediately. when all 3 functions return, they refer to the variable i has become 3, so the final result is 9.
Rewrite code
>>> def count ():
... def f (j):
... return lambda:j*j-- reference J variable,lambda anonymous function without parameter
... fs = []
... for i in range (1, 4):
... fs.append (f (i))
... return FS
>>> F1 ()
1
>>> F2 ()
4
>>> F3 ()
9
This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1820912
Python Functional Programming--return function