Variable value changes referenced in the python Closure

Source: Internet
Author: User

Variable value changes referenced in the python Closure
The closure feature of python is that the returned function also references the local variables of the outer function. Therefore, to correctly use the closure, make sure that the referenced local variables cannot be changed after the function returns. As follows:

Def count (): fs = [] for I in range (1, 4): def lazy_count (j): def cou (): return j * j return cou r = lazy_count (I) fs. append (r) return fsf1, f2, f3 = count () print f1 (), f2 (), f3 ()

 

If the above Code is written as follows:
Def count (): fs = [] for I in range (1, 4): def f (): return I * I fs. append (f) return fsf1, f2, f3 = count ()

 

The final f1, f2, and f3 values are all 9, because f () in the count () function obtained in this line: 1f1, f2, f3 = count () the I in the function has been iterated to 3, and the final result can only be 9 9 9. In the code given at the beginning, f1, f2, and f3 actually get a sequence, the variable in the outer function of the closure referenced when calculating each element in this sequence changes with iteration, from 1 to 3, at the same time, the element values obtained from this iteration are appended to the sequence and returned. The final result of Gu is 1 4 9.

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.