Understanding closures through Python

Source: Internet
Author: User

Let's look at a simple function.

1 def Calc_sum (1st):
2 def lazy_sum ():
3 return sum (1st)
4 return Lazy_sum

At this point it is not able to move the lazy_sum to the outside of the calc_sum because it references the calc_sum parameter lst.

Such an inner layer function refers to the variable of the outer function (parameter is also a variable). It 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 external function, so to properly use closures, it is necessary to ensure that the referenced local variables do not change after the function returns.

Down we'll see a case that should be understood:

The actual results are all 9.

The reason is that when the count () function returns three functions, the value of the variable I referenced by these three functions has become 3, and since F1,F2,F3 is not called, they do not calculate i*i, when F1 is invoked: The result is 9.

Therefore, the return function does not drink any loop variables, or subsequent variables that change loudly.

After rewriting the count () function like this, he can return 149 correctly.

Understanding closures through Python

Related Article

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.