---
title: "[转]Python闭包的改进 - 很好的分析，之前自己不懂."
author: "idning"
date: "2011-12-23T16:24:53Z"
tags: []
categories: ["非技术"]
slug: "python"
draft: false
lastmod: "2011-12-23T16:24:53Z"
id: 1323256
url: "https://idning.iteye.com/blog/1323256"
---

## [Python闭包的改进](http://www.cn-cuckoo.com/2009/01/04/the-enhancement-of-closure-281.html "本书永久链接 Python闭包的改进")

### 2009年01月4日 [原创](http://www.cn-cuckoo.com/category/authorship "查看 原创 中所有文章"), [编程技术](http://www.cn-cuckoo.com/category/programming "查看 编程技术 中所有文章")

Python也支持闭包，但在Python3.0以前，闭包不能访问外部函数中的局部变量。Python3.0为此引入了nonlocal关键字，从而完善了闭包访问外部变量的机制。

在Python2.6中，如果像下面这样定义函数：

`1` `>>> def` `outerFun():`

`2` `outerVar =` `0`

`3` `def` `innerFun():`

`4` `outerVar +=` `1`

`5` `print` `outerVar`

`6` `return` `innerFun`

然后，调用outerFun返回的闭包，会导致错误：

`1` `>>> f =` `outerFun()`

`2` `>>> f()`

`3`  

`4` `Traceback (most recent call last):`

`5` `File` `"<pyshell#15>", line 1, in` `<module>`

`6` `f()`

`7` `File` `"<pyshell#12>", line 4, in` `innerFun`

`8` `outerVar +=` `1`

`9` `UnboundLocalError: local variable 'outerVar'` `referenced before assignment`

把错误消息“UnboundLocalError: local variable ‘outerVar’ referenced before assignment”翻译成中文，就是“未绑定局部变量：引用局部变量’outerVar’之前没有赋值”。啥意思呢？在内部函数innerFun中，outerVar被Python解释器看成是内部函数innerFun中的局部变量，并不是我们认为的外部（函数outerFun中的）变量。即在innerFun中，outerVar只是一个尚未赋值的变量——尽管与外部的outerVar同名，因此不能执行加法计算。Python3.0以前的版本提供了global关键字，通过这个关键字能够在函数内部引用并重新绑定（修改）全局变量：

`1` `>>> x =` `1`

`2` `>>> def` `c():`

`3` `global` `x`

`4` `x +=` `1`

`5` `print` `x`

`6`  

`7` `>>> c()`

`8` `2`

这里通过global关键字在函数c的局部作用域中引用了全局变量x，因此就可以重新绑定（修改）全局变量了。虽然能访问和修改全局变量，但还是不能解决闭包访问外部函数变量的问题。为此，Python3.0增加了一个新关键字——nonlocal，用于在嵌套函数中访问外部变量：

`01` `>>> def` `outerFun():`

`02` `outerVar =` `0`

`03` `def` `innerFun():`

`04` `nonlocal outerVar   # 使用nonlocal引用外部函数变量`

`05` `outerVar +=` `1`

`06` `print(outerVar) # 注意，print在Python3.0中是函数，不是语句`

`07` `return` `innerFun`

`08`  

`09` `>>> f =` `outerFun()`

`10` `>>> f()`

`11` `1`

`12` `>>> f()`

`13` `2`

而且，此时的外部变量对于内部的函数而言是共享的：

`01` `>>> def` `outerFun():`

`02` `outerVar =` `0`

`03` `def` `innerFun():`

`04` `nonlocal outerVar`

`05` `outerVar +=` `1`

`06` `print(outerVar)`

`07` `def` `innerFun2():`

`08` `nonlocal outerVar`

`09` `outerVar *=` `2`

`10` `print(outerVar)`

`11` `return` `[innerFun,innerFun2] # 通过列表返回两个函数`

`12`  

`13` `>>> ff =` `outerFun()`

`14` `>>> ff[0]()`

`15` `1`

`16` `>>> ff[1]()`

`17` `2`

`18` `>>> ff[1]()    # 连续调用两次innerFun2`

`19` `4`

`20` `>>> ff[0]()    # 结果表明，两个闭包共享同一个变量`

`21` `5`

关于这一点改进的详细内容，请参见PEP（Python Enhancement Proposals，Python改进建议）3104：[Access to Names in Outer Scopes](http://www.python.org/dev/peps/pep-3104/ "http://www.python.org/dev/peps/pep-3104/")。