Python Closure:为什么在更改数字时允许更改闭合字典?
当我尝试更改闭合
def a():
x = {'a':'b'}
def b():
x['a'] = 'd'
print(x)
return b
>>> b = a()
>>> b()
{'a':'d'}
输出中的字典时,该代码效果很好,可以满足我的期望。但是,为什么下面的代码不起作用?
def m():
x = 1
def n():
x += 1
print(x)
return n
>>> n = m()
>>> n()
unboundlocalerror:locultlocalerror:locallible'x'在分配之前引用了
老实说,我知道我们可以使用非局部x
语句来解决此问题
但是有人可以对我更深入地解释原因吗? 字典和数字之间的差异
谢谢!
this code works well when I try to change dictionary in closure
def a():
x = {'a':'b'}
def b():
x['a'] = 'd'
print(x)
return b
>>> b = a()
>>> b()
{'a':'d'}
output is meeting my expectation. but why the code below doesn't work?
def m():
x = 1
def n():
x += 1
print(x)
return n
>>> n = m()
>>> n()
UnboundLocalError: local variable 'x' referenced before assignment
Honestly, I've known that we can use nonlocal x
statement to solve this problem
But can anybody explain the reason more deeply for me? what the difference between a dictionary and a number
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
python有一个很好的 FAQ 专门针对此。
简而>对象,您修改相同的对象,因此您不会重新分配变量。如果整数是不可变的,则通过执行
+=
创建一个新对象并将其放入x
中。由于X现在已在内部函数内定义,但是您正在尝试从外部功能带来数据,因此您有问题。您可以使用
id()
检查是否是同一对象。Python has a great FAQ specifically on this.
In short, when you modify a dictionary, or any mutable object, you modify the same object, so you don't re-assign the variable. In case of an integer, since it's immutable, by doing a
+=
you create a new object and put it intox
. Since x is now defined inside the inner function, but you're trying to bring data from the outer function, you have an issue.You can check if it's the same object using
id()
.