Python Functional Programming (3)--closures

Source: Internet
Author: User

The inner layer function refers to the variable of the outer function (parameter also the variable), and then returns the case of the inner layer function, called the closure (Closure). The feature of closures is that the returned function also refers to the local variables of the outer function, so to properly use closures, it is necessary to ensure that the referenced local variables do not change after the function returns.

example: you want to return 3 functions at a time, calculate 1x1,2x2,3x3 separately:
def Count ():
    fs = []
    for I in range (1, 4):
        def f ():
            return i*i
        fs.append (f)
    print (FS)
    return FS

F1, F2, F3 = count ()
Print (F1 (), F2 (), F3 ())
# The results are all 9. The reason is that when the count () function returns 3 functions, the value of the variable I referenced by these 3 functions has become 3.
# because F1, F2, F3 are not called, so they do not calculate i*i at this time, when F1 is invoked: 9.
# Therefore, the return function does not refer to any loop variables, or to subsequent variables that change.

The return closure cannot refer to a loop variable, please rewrite the count () function to correctly return a 1x1, 2x2, 3x3 function that can be computed.
def count1 ():
fs = []
For I in range (1, 4):
def F (j):
def g ():
return j*j
return G
result = f (i)
fs.append (Result)
print (FS)
return FS
A1, A2, a3 = Count1 ()
Print (A1 (), A2 (), A3 ())

Python Functional Programming (3)--closures

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.