Python Learning Note (ix) return function

Source: Internet
Author: User

Excerpt: Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 001431835236741e42daf5af6514f1a8917b8aaadff31bf000

This article is completely used for personal review study, invasion and deletion;

function as return value

Higher-order functions can also return a function as a result value, in addition to the ability to accept functions as parameters.

What if you do not need to sum immediately, but in the later code, as necessary to calculate what to do? Instead of returning the result of a sum, you can return a function that sums:

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

When we call lazy_sum() , we return the SUM function instead of summing the result:

>>> f = lazy_sum (1, 3, 5, 7, 9)>>> F<function lazy_sum.<locals>.sum at 0x101 C6ed90>

When the function is called f , the result of the sum is really computed:

>>> F ()25

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

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

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

f1()and f2() the results of the call are not affected.

Closed Package

Notice that the returned function references a local variable within its definition, args so when a function returns a function, its internal local variables are also referenced by the new function.

Another problem to be aware of is that the returned function is not executed immediately, but only when it is called. f() Let's look at an example:

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

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

You may think that the call f1() , f2() and the f3() result should be 1 ,, but the 4 9 actual result is:

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

All of them 9 ! The reason is that the returned function refers to the variable i , but it is not executed immediately. When all 3 functions are returned, the variables they refer to are i already turned 3 , so the end result is 9 .

One thing to keep in mind when returning closures is that the return function does not refer to any loop variables, or to subsequent variables that change.

What if you must refer to a loop variable? The method is to create a function that binds the current value of the loop variable with the parameter of the function, regardless of how the loop variable is subsequently changed, and the value that is bound to the function parameter remains the same:

def count ():     def F (j):         def g ():             return j*J        return  g    = []    for  in range (1, 4):        #  F (i) is executed immediately, so the current value of I is passed in F ()    return Fs

And look at the results:

>>> F1, f2, F3 = count ()>>> F1 ()1>>> F2 ()4>>> f3 () /c3>9
Summary

A function can return a result of a calculation, or it can return a function.

When returning a function, keep in mind that the function is not executed, and do not refer to any variables that may change in the return function.

Python Learning Note (ix) return function

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.