Concept description of closures in Python functions

Source: Internet
Author: User

Concept description of closures in functions

Closures:
The inner layer function is referred to as the non-global variable of the outer layer function, it is called the closure


Determine the closure method. _closure_:

Returning valid information after execution is a closure, and returning none is not a closure.

Example 1: It's a closed packet.
def wrapper ():
name = ' Alex '
def inner ():
Print (name)
Inner ()
Print (inner.__closure__) # (<cell at 0x006121d0:str object at 0x00227380>,)
Wrapper ()
Results:

Alex
<cell at 0x006121d0:str object at 0x00227380>


Example 2: not closures
name = ' Alex '

def wrapper ():
def Inner ():
Span style= "COLOR: #00ff00" > print (name)
inner ()
print (inner.__closure__) # None
wrapper ()
result:
Alex
None

closure function:

special mechanism for closures:
The Python interpreter encounters a closure, a special mechanism for closures is that closures do not release with the end of the function. The temporary space for this closure will not be freed after the function is run.
or after the function ends, the non-global variables that the function references to the upper layer are still present and will not be emptied. The non-global variable referenced by
is not closed and is still in memory and is invoked directly from that memory when it is reused.

Use of closures:
Crawler
Decorative Device

     Crawler Examples:
def index ():
url = "Http://www.xiaohua100.cn/index.html"
Def get ():
return Urlopen (URL). Read ()
return get

Xiaohua = index () # get
Content = Xiaohua ()
Content1 = Xiaohua ()
Content2 = Xiaohua ()
Print (Content.decode ())

Concept description of closures in Python functions

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.