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