Python uses functions as a return value and a tutorial for implementing closures _python

Source: Internet
Author: User

function as the return value

In addition to accepting functions as arguments, higher-order functions can return functions as result values.

Let's implement a sum of variable parameters. In general, the function of summation is defined in this way:

def calc_sum (*args):
  ax = 0 for
  n in args:
    ax = ax + N-return
  ax

But what if you don't need to sum it right now, but in the code that follows, what to do if you need to? Instead of returning the result of the summation, you can return the SUM function!

def lazy_sum (*args):
  def sum ():
    ax = 0 for
    n in args:
      ax = ax + n return
    ax
  -return sum

When we call Lazy_sum (), we return not the sum, but the summation function:

>>> f = lazy_sum (1, 3, 5, 7, 9)
>>> f
<function sum at 0x10452f668>

When the function f is called, the result of the summation is really calculated:

>>> f ()
25

In this example, we define the function sum in the function lazy_sum, and the internal function sum can refer to the arguments and local variables of the external function lazy_sum, and when Lazy_sum returns the sum of the functions, the related arguments and variables are stored in the returned function, which is called " The program structure of closure (Closure) has great power.

Note that when we call Lazy_sum (), each call returns a new function, even if the same argument is passed in:

>>> f1 = lazy_sum (1, 3, 5, 7, 9)
>>> F2 = lazy_sum (1, 3, 5, 7, 9)
>>> f1==f2
False

The invocation results of F1 () and F2 () do not affect each other.
Closed Bag

Note that the returned function refers to the local variable args within its definition, so when a function returns a function, its internal local variables are also referenced by the new function, so the closure package is simple and difficult to implement.

Another issue to note is that the returned function does not execute immediately, but until F () is invoked. Let's take a look at an example:

def count ():
  fs = []
  for I in range (1, 4):
    def f (): Return
       i*i
    fs.append (f) return
  FS

F1 , F2, F3 = count ()

In the example above, each loop creates a new function and then returns the 3 functions that were created.

You may think that calling F1 (), F2 () and F3 () results should be 1,4,9, but the actual result is:

>>> F1 ()
9
>>> F2 ()
9
>>> f3 ()
9

It's all 9! The reason is that the returned function refers to the variable I, but it is not executed immediately. When 3 functions are returned, the variable I referenced is already 3, so the final result is 9.

One thing to keep in mind when returning a closure is that the return function does not refer to any loop variable, or to a variable that changes later.

What if you must refer to a loop variable? The method is to create a second function, with the function's argument binding the current value of the variable, regardless of the subsequent changes to the loop variable, the value that is bound to the function parameter is unchanged:

>>> def count (): ...   FS = []
...   For I in range (1, 4):
...     def f (j):
.       . def g ():         .. Return j*j ...       Return g ...     Fs.append (f (i))
...   Return FS
... 
>>> F1, F2, F3 = count ()
>>> F1 ()
1
>>> f2 ()
4
>>> f3 () C31/>9

The disadvantage is that the code is longer and the lambda function can be used to shorten the code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.