Python's closures

Source: Internet
Author: User
Tags closure

If in an intrinsic function, a reference is made to a variable that is in an outer scope (but not at the global scope), then the intrinsic function is considered a closure (closure).  variables defined within an external function but referenced or used by an intrinsic function are called free variables.

Closures are an important concept in functional programming, and Scheme and Haskell are two of the functional programming. Closures are syntactically simple (as simple as internal functions) but still powerful.

So why would you want to use closures?
Closures are useful for installing calculations, hiding states, and switching freely between function objects and scopes.

closures in gui< Span class= "FONTSTYLE0" > or in many api event-driven programming that supports callback functions is useful. data.   callback is a function. Closures are also functions, but they can carry some additional scopes.   additional scopes.
Closures and function calls are not much related, but rather about using variables defined in other scopes.

 def  counter (start_at=0): Count  =< Span style= "color: #000000;" >[START_AT]  def   INCR (): Count[0]+=1 return   Count[0]  return   incr;  if  __name__  ==  __main__   :  print  (Counter (0) ()) 

counter () The only thing to do is to accept an initialized value to start counting and assign that value to the list count the only member. Then define an intrinsic function that incr () by using the variable internally count We created a closure because it now carries the entire counter () incr () increased the running count

And then the last magic is counter () returns a incr, a (callable ) function object.

Note Counter (0) (), counter (0) returns the INCR, a callable function object, so add () later





Python's 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.