Python function closure ()

Source: Internet
Author: User

Closures (closure)

When a function internally defines a function, and the internal function applies an external function parameter or a local variable, when the intrinsic function is treated as the return value, the relevant parameters and variables are stored in the return function, and the result is called the closure

Example1:

1 defTest (*args):2     3     deftest_1 ():4RST =05          forIinchArgs#The parameters outside the function are used here6RST + =I7         returnrst8     returnTest_1#returns a function as a return value, with related parameters and variables stored in the returned function9 TenA = Test () One Print(A ())

This is a common closure.

Closures also have deceptive places.

Example2:

defcount (): FS= []    #A list is defined here.     forIinchRange (1,4):        #defines a function f        #F is the structure of a closure        deff ():returnI*i#It's not going to be calculated immediately when we return.fs.append (f)returnfsf1,f2,f3=count ()Print(F1 ())Print(F2 ())Print(F3 ())#9#9#9#[finished in 0.2s]#Why is it 999, the reason for this is that the return function references the variable i,#and I is not executed immediately, but isosceles three functions are returned in a unified execution#at this point I has become 3, and the final call returns to 3*3 .# 

The above problem results in the following: When you return a closure, you cannot reference any of the loop variables

Workaround:

and set up a function outside.

Example3:

defcount2 (): FS= []    #A list is defined here.    defF (i):#I passed in as a parameter        defg ():returnI*i#I'll do it right here when I return.        returng forIinchRange (1,4): Fs.append (f (i))returnfsf1,f2,f3=Count2 ()Print(F1 ())Print(F2 ())Print(F3 ())#1#4#9

Python function 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.