闭包(内部函数用了外部函数的数据)

闭包(内部函数用了外部函数的数据)



内部函数 引用了外部函数的变量, 内部的函数 就叫 闭包

复制代码
# def func():
#     name='egon'
#     def inner():
#         print(name)
#     return inner
#     # print(inner.__closure__)   # 使用外部参数的个数 (<cell at 0x0000000000120C78: str object at 0x0000000001DCC110>,)  判断闭包
# inner=func()
#
# inner()   # 执行的时候只创建一次 节省空间
# inner()
# func()()  #每次执行都创建一次name
# func()()
复制代码

     闭包例子

复制代码
from urllib.request import urlopen

def get_url():
    url=r'https://i.cnblogs.com/PostDone.aspx?postid=7452088&actiontip=%E4%BF%9D%E5%AD%98%E4%BF%AE%E6%94%B9%E6%88%90%E5%8A%9F'

    # 可能有好多网页

    def inner():
        re=urlopen(url).read().decode('utf-8')
        print(re)
    return inner

    # 用闭包可以避免多次打开数据;

get_web_content=get_url()
get_web_content()
复制代码


装饰器 是 闭包(内置函数) 的一种应用
让变量不会容易改变,并且不会每次都会变量创建一次
原文地址:https://www.cnblogs.com/hzqblog/p/7515700.html