Python Advanced closure

Source: Internet
Author: User

<title>Closed Package</title> Closed Package

functions defined inside a function are the same as externally defined functions, except that they cannot be accessed externally:

1.def g():
2. print‘g()...‘
3.def f():
4. print‘f()...‘
5. return g

Move the definition of G into the inside of function f, preventing other code from calling G:

1.def f():
2. print‘f()...‘
3. def g():
4. print‘g()...‘
5. return g

But

1.def calc_sum(lst):
2. def lazy_sum():
3. return sum(lst)
4. return lazy_sum

This is not possible to move the lazy_sum to the outside of Calc_sum because it references the calc_sum parameter lst.
Such an inner layer function refers to a variable of the outer function, and then returns the case of an inner layer function, called a closure (Closure).

the feature of closures is that the returned function also refers to the local variables of the outer function, like this:

1.#希望一次返回3个函数, calculate 1*1,2*2,3*3 separately
2. def Count():
3.Fs=[]
4. forIinchRange1,4):
5. def F():
6. returnI*i
7.Fs.append (f)
8. returnFs
9.F1,f2,f3=count ()

You might think that calling F1 (), F2 (), F3 (), the result should be 1,4,9, but the actual result is 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 at this point they do not calculate i*i, when F1 is invoked:

1.>>> f1()
2.9 #因为f1现在才计算i*i,但现在i的值已经变成了3

Therefore, the return function does not refer to any loop variable or any subsequent variable that will change

So how can this program be rewritten so that it correctly returns a function that calculates 1*1,2*2,3*3?

1. def Count():
2.Fs=[]
3. forIinchRange1,4):
4. def F(j):
5. def G():
6. returnJ*j
7. returnG
8.R=f (i)
9.Fs.append (R)
. returnFs
One by one .F1,f2,f3=count ()
.PrintF1 (), F2 (), F3 ()

Python Advanced closure

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.