关于python闭包的问题

7 views
Skip to first unread message

Mu Qiao

unread,
Jul 31, 2009, 5:50:43 AM7/31/09
to pyth...@googlegroups.com
大家好,我最近学习python,对于python的闭包有点不明白,下面两段代码:
def getadd():
    count=[0]
    def incr(x):
        count[0]+=x
        print(count[0])
    return incr
a=getadd()
a(1)

def getadd():
    count=0
    def incr(x):
        count+=x
        print(count)
    return incr
a=getadd()
a(1)

为什么第二段代码不能成功执行,会说'count' referenced before assignment,但是第一段以列表的形式就没有问题呢?请大家指点

--
Best wishes,
Qiao Mu

monitor_yhr

unread,
Jul 31, 2009, 9:35:03 AM7/31/09
to pyth...@googlegroups.com
的确是这样的

第二段中的 count+=x 表达式是一个赋值表达式,这会创建一个本地的count变
量,但是此表达式中又需要引用count,即count = count + x,这就是错误的由来

第一段中对count仅仅是引用,没有赋值操作,count[0]+=x 是赋值给count的第一
个元素,该元素已经存在,没有错误

在 2009-07-31五的 17:50 +0800,Mu Qiao写道:

mu

unread,
Jul 31, 2009, 10:16:50 AM7/31/09
to python-cn`CPyUG`华蟒用户组(中文Py用户组)
那也就是说python的闭包,内函数只能对外函数变量所引用的对象进行更改,但不能对该引用进行重新赋值?

Heroboy

unread,
Jul 31, 2009, 11:13:32 AM7/31/09
to pyth...@googlegroups.com

Python的文档这么说的:

A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block. If the definition occurs in a function block, the scope extends to any blocks contained within the defining one, unless a contained block introduces a different binding for the name. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods.

count += x 就相当于对count重新bind了,所以count被认为是局部变量。

2009/7/31 mu <qia...@gmail.com>

mu

unread,
Aug 1, 2009, 1:22:23 AM8/1/09
to python-cn`CPyUG`华蟒用户组(中文Py用户组)
非常感谢:)

On 7月31日, 下午11时13分, Heroboy <yangwei...@gmail.com> wrote:
> 4.1 Naming and binding
>
> Python的文档这么说的:
>
> A *scope* defines the visibility of a name within a block. If a local


> variable is defined in a block, its scope includes that block. If the
> definition occurs in a function block, the scope extends to any blocks

> contained within the defining one,* unless a contained block introduces a
> different binding for the name*. The scope of names defined in a class block


> is limited to the class block; it does not extend to the code blocks of
> methods.
> count += x 就相当于对count重新bind了,所以count被认为是局部变量。
>

> 2009/7/31 mu <qiao...@gmail.com>

Reply all
Reply to author
Forward
0 new messages