Analyze a closure function

Source: Internet
Author: User

Analyze a piece of code


def count (): FS = [] for I in range (1, 4): Def f (): Return i*i fs.append (f) Return FSF1 , F2, F3 = count ()

First say the bottom F1,F2,F3=COUNRT ()


F1, F2, F3 = count () equals [F1, F2, f3] = [F, F, F]

Equivalent to F1 = f

F2 = f

F3 = f


Fs.append (f)

Note here that the function f is added to FS instead of the value returned by F, you can try to execute the command:

>>> f<function F at 0x00000283bf7706a8>>>> count () [<function count.<locals>.f at 0x00000283bf770840>, <function count.<locals>.f at 0x00000283bf7707b8>, <function count.<locals >.F at 0x00000283bf770598>]

It is visible that a list of three functions is returned. So when executing code

F1, F2, F3 = count ()

, the three functions that count contains are assigned to F1, F2, F3, respectively, in index order, and i=3 at this time, so the function evaluates to 9.

>>> F1 () 9>>> F2 () 9>>> F3 () 9

In Python everything is the object, and the variable I only one, in three cycles, it points to the object changes, and the function f1,f2,f3 in the actual execution of the address I pointed to the actual storage data has become 3, so three times the result is the same.


Fs.append (f) Here the f is just a pointer is not a function so do not execute until when to execute so after the FOR loop 3 times I became 3 F always after all the execution is done before going to call because it is placed in the ""


No matter how many times it is called Count one of his for has been executed 3 times I has become 3 so at this time the F function used is of course 3

This article is from "Life is waiting for Gordo" blog, please make sure to keep this source http://chenx1242.blog.51cto.com/10430133/1769485

Analyze a closure function

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.