[Python3] 036 functional programming function returns

Functional Programming

Return function

  • Function returns a specific value
  • It may also return a result as a function of

1. primer

1.1 Define a common function

>>> def func():
...   print("abc")
...   return None
...
>>> my_func = func()
abc
>>> print(my_func)
None
>>> my_func
>>> 

1.2 as a function returns a return value

  • Function is returned in the body of the function definition of
In [1]: def out_func():
   ...:     def in_func():
   ...:         print("in func")
   ...:         return 100
   ...:     return in_func
   ...:
   ...:

In [2]: f = out_func()

In [3]: print(type(f))
<class 'function'>

In [4]: print(f)
<function out_func.<locals>.in_func at 0x000001B9B99D6BF8>

In [5]: f()
in func
Out[5]: 100

In [6]: 

1.3 List of the function parameters return

>>> def out_func(*args):
...   def in_func():
...     rst = 0
...     for i in args:
...       rst += i
...     return rst
...   return in_func
...
>>> f1 = out_func(1, 2, 3, 4, 5)
>>> f1()
15
>>> f2 = out_func(6, 7, 8, 9, 10)
>>> f2()
40


2. Closure closure

  • When a function is defined within the function, application parameters and the internal function of the external function or local variables, the function is used as the internal return value, parameters and variables are stored in the function returns, the result of this, called closure
  • Above 1.3 the function returns the list of parameters of an example of a standard closure structure is

2.1 common pit about closures

>>> def out_func():
...   res = []
...   for i in range(1, 4):
...     def in_func():
...       return i * i
...     res.append(in_func)
...   return res
...
>>> f1, f2, f3 = out_func()
>>> f1()
9
>>> f2()
9
>>> f3()
9
>>> 

2.2 of the reasons contributing to this situation

  • Function that returns a reference to the variable i , i is not executed immediately, but wait until three functions return of only unity, in which case i have become 3, the final call when the return is 3 * 3

  • Thus: return closure function can not reference any return loop variable

2.3 Solution

  • Then creating a function, binding loop variable parameter of the function of the current value, how to change the future regardless of whether the loop variable, function parameter values ​​have been bound not change
>>> def out_func():
...   def in1(n):
...     def in2():
...       return n * n
...     return in2
...   res = []
...   for i in range(1, 4):
...     res.append(in1(i))
...   return res
...
>>> f1, f2, f3 = out_func()
>>> f1()
1
>>> f2()
4
>>> f3()
9
>>> 

Guess you like

Origin www.cnblogs.com/yorkyu/p/12074849.html