Variable value change issues referenced in Python closures

Source: Internet
Author: User

Python's Closed Package the feature 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 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, F3 are all 9, because this line:

F1, F2, F3 = count ()

The f () function in the resulting count () function has been iterated to 3 and the final result can only be 9 9 9

In the code that was just given, F1,f2,f3 actually got a sequence, and the variables in the enclosing function that were referenced during each element of the sequence were changed from 1 to 3 in the iteration, and the element value of the iteration was calculated append the return of the input sequence, and the final result was 1 4 9.

This article is from the "Keep_study_zh" blog, make sure to keep this source http://zhkpsty.blog.51cto.com/9013616/1695120

Variable value change issues referenced in Python 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.