跟着太白老师学python day11 闭包 及在爬虫中的基本使用

闭包的基本概念: 闭包 内层函数对外层函数的变量(不包括全局变量)的引用,并返回,这样就形成了闭包

闭包的作用:当程序执行时,遇到了函数执行,它会在内存中开辟一个空间,如果这个函数内部形成了闭包,

那么他就不会随着函数的执行结束而消失

闭包的基本例子

def wrapper():
    name = 'alex'
    def inner():
        print(name)  #inner函数引用了name函数,形成了闭包
    print(inner.__closure__)
    return inner()

wrapper()

name = 'alex'
def wrapper(n):
    #将全局变量传递到函数中相当于在wrapper函数内创建:n = 'alex'
    def inner():
        print(n)
    print(inner.__closure__)  # 因此inner 也是闭包
    return inner
wrapper(name)

闭包在爬虫中的基本使用, 爬完一次以后,他不会随着程序的结束而消失,因为下次使用时不需要再开辟空间

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.decode('utf-8'))
原文地址:https://www.cnblogs.com/my-love-is-python/p/9493702.html