学习了啥叫闭包,光看这俩字认识但完全不知道啥意思,现在弄明白了,就相当于在函数中声明一个类似glogal的变量,但在可函数体之外还可以访问的变量,就是函数注销了这个变量依然还在内存。
```
#学习闭包
#用作简单的一个计数器
def count():
count=3
def print_count():
nonlocal count
count+=1
print('我还保留着主函数的变量值',count)
print('我是主函数已经执行完')
return print_count
a=count()
b=count()
a()
a()
for i in range(3):
a()
```
```
#学习闭包
#用作简单的一个计数器
def count():
count=3
def print_count():
nonlocal count
count+=1
print('我还保留着主函数的变量值',count)
print('我是主函数已经执行完')
return print_count
a=count()
b=count()
a()
a()
for i in range(3):
a()
```
展开
25
2
![[吃瓜群众]](http://lf-web-assets.juejin.cn/obj/juejin-web/xitu_juejin_web/img/jj_emoji_10.42a731c.png)