可以看出在第一个函数中只改到了 local namespace,而第二个函数加入了 global 才让 num 变成在 global namespace 之中。

Closure 也是个函数,但其绑定了一个环境,包含了一些 free variables 在之中。而这些 free variable 即使在定义的作用域已经无效了的时候仍然能够被使用。以下为一个例子:

可以用 __code__ 以及 __closure__ 来了解 closure 中的细节。

如果少了第六行中的 nonlocal 会发生此错误:local variable 'count' referenced before assignment。因此 nonlocal 的目的即为让这两个变数能为 free variables 而不只是 local variables。