def createCounter(): count = 0 def counter(): nonlocal count count += 1 print(id(count)) return count return counter
def createCounter(): count = [0] def counter(): count[0] += 1 print(id(count)) return count[0] return counter
2003791328 2003791360 2003791392 2003791424 2003791456 1 2 3 4 5 2003791328 2003791360 2003791392 2003791424 测试通过!
1426349774792 1426349774792 1426349774792 1426349774792 1426349774792 1 2 3 4 5 1426349775240 1426349775240 1426349775240 1426349775240 测试通过!
<p>上面两段代码我都输出了其中的内存地址,可以看到,第一种方法的内存地址在不断修改,每次调用counter函数count都被重新指向,这也就是为什么需要用到<code>nonlocal()</code>而调用list,内存地址没有变,指示改变了指向的值
看了你这个解释,感觉懂了
Sign in to make a reply
邹lh
<p>上面两段代码我都输出了其中的内存地址,可以看到,第一种方法的内存地址在不断修改,每次调用counter函数count都被重新指向,这也就是为什么需要用到<code>nonlocal()</code>而调用list,内存地址没有变,指示改变了指向的值