自学Python--函数闭包

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41402059/article/details/82288126

闭包:嵌套函数且内部函数调用外部函数的变量

以下如果inner函数未调用外部函数的a,则a不是闭包

def outer():
    a = 1
    def inner():
        print(a)
    print(inner.__closure__)
outer() # (<cell at 0x000001367FAA0C48: int object at 0x00000000521DC6B0>,) cell关键字说明闭包
print(outer.__closure__) # None 非闭包
 

在函数外部调用内部函数:

def outer():
    a = 1
    def inner():
        print(a)
    return inner
inn = outer()
inn() # 1 a不会释放

闭包的应用:

from urllib.request import urlopen


def get_url():
    url = 'http://www.xiaohua100.cn/index.html'
    def get():
        res = urlopen(url).read()
        print(res)
    return get
# 节省url变量资源
get_f = get_url()
get_f()
get_f()
get_f()
get_f()
get_f()

猜你喜欢

转载自blog.csdn.net/weixin_41402059/article/details/82288126