Python Advanced Tutorial-return function

Source: Internet
Author: User

function as return value

In addition to receiving functions as parameters, higher-order functions can also return functions as result values.

To implement the summation of a mutable parameter. In general, the function of summing is defined like this:

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

However, if you do not need to sum immediately, but in the following code, as necessary to calculate how to do? You can return the sum of the function without returning the result of the sum

def lazy_sum (*args):    def  sum ():        = 0        for in  args:            + =        nreturn     axreturn  sum >>> f = lazy_sum (1,3,5,7,9)>>> F ()25

When we call Lazy_sum (), the return is not the result of the summation, but the sum function, when the function f is called, the result of summing is really computed.

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

When Lazy_sum () is called, 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 = =  F2false

F1 and F2 call results do not affect each other.

Closed Package

Notice that the returned function references the local variable args within its definition, so when a function returns a function, its internal local variables are referenced by the new function, so it is not easy to implement them with a simple closure.

Another problem to be aware of is that the returned function is not executed immediately, but rather directly called F ():

def count ():     = []    for 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 three functions that were created.

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

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

All of them are 9! The reason is that the returned function refers to 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.

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, the value that is bound to the function parameter remains the same:

>>>defcount (): ... fs= []...      forIinchRange (1, 4):...         defF (j): ...defg (): ...returnj*J ...returng ... fs.append (f (i)) ...returnFS ...>>> F1, f2, F3 =count ()>>>F1 ()1>>>F2 ()4>>>f3 ()9

Python Advanced Tutorial-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.