我只是想知道,接下来的两个函数(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 ()
第一个函数抛出关于赋值前引用的异常,但第二个函数运行良好。有人可以解释一下,为什么 python 记住数组,而不是整数?
最佳答案
您正在为第一个嵌套函数中的 counter
名称赋值,使其成为局部变量。
在第二个例子中,你从来没有直接分配给counter
,使它成为一个自由变量,编译器正确地连接到父函数中的counter
。您永远不会重新绑定(bind)名称,您只是在更改 counter
引用的列表。
使用nonlocal
关键字将counter
标记为自由变量:
def first_example ():
counter = 0
def inc_counter ():
nonlocal counter
counter += 1
for i in range (10):
inc_counter()
关于python - Python 中的类型及其可见性之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20051730/