阿巴阿巴阿巴,老Amy 来啦~由于闭包这家伙是块难啃得的骨头,所以 老Amy 就想着用一篇逐字稿帮助大家来搞定它!
首先,在 get 闭包这个知识点之前,我们已经知道了函数的作用域。那现在考考大家,思考如下代码是否有问题?
def test():
a = 1
def test_in():
a += 1
print(a)
return test_in
res = test()
res()
那如果说大家觉得 no problem 的话,那你就把该代码拷贝到你的 pycharm 中,就会发现 OMG,怎么报错了呢?
其实就是因为在 test 这个函数中的 a 变量作用域是 enclosing ,那在 test_in 当中对 a 进行了 a += 1 的操作。此时,程序就不太明白 test_in 中的 a,是local还是enclosing ,所以报错。解决方案或详细解释参考:链接: https://blog.csdn.net/weixin_44352981/article/details/110819292.
此处代码应将 test_in 中的变量声明为非局部变量,如下:
def test():
a = 1
def test_