为什么这个空的dict可以共享引用? [英] Why does this empty dict break shared references?

查看:117
本文介绍了为什么这个空的dict可以共享引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现一些Python行为让我感到困惑。

I have found some Python behavior that confuses me.

>>> A = {1:1}
>>> B = A
>>> A[2] = 2
>>> A
{1: 1, 2: 2}
>>> B
{1: 1, 2: 2}

到目前为止,预期。 A和B都引用相同的,可变的,字典的和改变的,改变了另一个。

So far, everything is behaving as expected. A and B both reference the same, mutable, dictionary and altering one alters the other.

>>> A = {}
>>> A
{}           # As expected
>>> B
{1: 1, 2: 2} # Why is this not an empty dict?

为什么 A B 不再引用同一个对象?

Why do A and B no longer reference the same object?

我看到这个问题: Python空的dict不被引用传递,它验证了这个行为,但答案解释了如何修复提供的脚本不是为什么会出现这种情况。

I have seen this question: Python empty dict not being passed by reference? and it verifies this behavior, but the answers explain how to fix the provided script not why this behavior occurs.

推荐答案

这是一个图形表示*:

A = {1: 1} 
# A -> {1: 1}
B = A
# A -> {1: 1} <- B
A[2] = 2
# A -> {1: 1, 2: 2} <- B
A = {}
# {1: 1, 2: 2} <- B    
# A -> {}

A = {} 创建一个全新对象,并将标识符 A 重新分配给它,但影响 B 或以前引用的字典 A 。您应该阅读这篇文章,它涵盖了这样的事情。

A = {} creates a completely new object and reassigns the identifier A to it, but does not affect B or the dictionary A previously referenced. You should read this article, it covers this sort of thing pretty well.

请注意,作为替代,您可以使用 dict.clear 方法来排除字典就地

Note that, as an alternative, you can use the dict.clear method to empty the dictionary in-place:

>>> A = {1: 1}
>>> B = A
>>> A[2] = 2
>>> A.clear()
>>> B
{}

As A B 仍然引用同一个对象,现在都看到空版本。

As A and B are still references to the same object, both now "see" the empty version.

* 对于第一个近似值 - 类似的引用行为在字典中也是,但由于值是不可变的,所以不太相关。

* To a first approximation - similar referencing behaviour is going on within the dictionary too, but as the values are immutable it's less relevant.

这篇关于为什么这个空的dict可以共享引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆