The study notes python closure

Closure function

Inside the play function contains not outside the scope of the name of a reference scope, the function is called the inner closure function

Function is called a function defined inside an internal function

Thanks to the scope of the relationship, we can not get the variables and functions inside the function. If we want to take it is how to do it? Return it! We all know that variable within the function we want to use in an external function, you can return directly to this variable, so if we want to call an internal function outside the function of function? It is not directly put the name of the function's return like? This is the closure function of the most common uses

def func():
    name = 'eva'
    def inner():
        print(name)
    return inner

f = func()
f()

Analyzing Method closure function closure

# __Closure__ output cell elements are: a closure function 
DEF FUNC (): 
    name = ' EVA ' 
    DEF Inner ():
         Print (name)
     Print (. Inner __closure__ )
     return Inner 

F = FUNC () 
F () 

# __closure__ is output None: without a closure function 
name = ' Egon ' 
DEF func2 ():
     DEF Inner ():
         Print (name)
     Print (Inner. __closure__ )
     return Inner 

F2 = func2()
f2()

Closure Nested

def wrapper():
    money = 1000
    def func():
        name = 'eva'
        def inner():
            print(name,money)
        return inner
    return func

f = wrapper()
i = f()
i()

Closure acquired Network Application Function

 

from urllib.request import urlopen

def index():
    url = "http://www.xiaohua100.cn/index.html"
    def get():
        return urlopen(url).read()
    return get

xiaohua = index()
content = xiaohua()
print(content)

 

 

 

Guess you like

Origin www.cnblogs.com/zhangcheng94/p/12182368.html