Python中类型之间的差异及其可见性

Evi*_*ton 2 python types exception function

我只是想知道,下两个函数之间有什么区别(Python 3.x)

def first_example ():
    counter = 0
    def inc_counter ():
        counter += 1
    for i in range (10):
            inc_counter ()

def second_example ():
    counter = [0]
    def inc_counter ():
        counter[0] += 1
    for i in range (10):
            inc_counter ()
Run Code Online (Sandbox Code Playgroud)

关于赋值之前引用的第一个函数抛出异常,但第二个函数运行良好.有人可以解释一下,为什么python会记住数组,而不是整数?

Mar*_*ers 5

您将counter在第一个嵌套函数中指定名称,使其成为局部变量.

在第二个示例中,您永远不会counter直接分配,使其成为自由变量,编译器正确连接到counter父函数.你永远不会重新绑定名称,你只是改变列表counter所指的.

使用nonlocal关键字标记counter为自由变量:

def first_example ():
    counter = 0
    def inc_counter ():
        nonlocal counter
        counter += 1
    for i in range (10):
        inc_counter()
Run Code Online (Sandbox Code Playgroud)