# ### 闭包的特点 # (1)闭包的特点: ''' 内函数使用了外函数的局部变量,外函数的局部变量与内函数发生绑定,延长该变量的生命周期 (实际内存给它存储了这个值,暂时不释放) ''' def outer(num): def inner(val): return num + val return inner func = outer(10) # func = inner res = func(21) # func(21) = inner(21) print(res) # res = num + val = 10 + 21 = 31 ''' 代码解析: num 接收到普通实参10 此刻 num = 10 func = outer(10) # func = inner res = func(21) # func(21) = inner(21) print(res) # res = num + val = 10 + 21 = 31 ''' # (2) 闭包的意义 # 模拟鼠标点击的操作 ''' # 如果使用全局变量num来进行统计,因为作用域太大,容易造成漏洞.不安全 num = 0 def click_num(): global num num+=1 print(num) # 调用一次函数,累加一次num click_num() click_num() click_num() num = 100 click_num() click_num() ''' # 闭包的意义: ''' 闭包可以优先使用外函数中的变量,并对闭包中的值起到了封装保护的作用.外部无法访问. ''' def click_num(): num = 0 def func(): nonlocal num num+=1 print(num) return func click_num = click_num() click_num() click_num() click_num() num = 100 click_num() click_num()