为什么 del 不做同样的事情? [英] Why doesn't del do the same thing?
问题描述
为什么下面的代码改变了两个变量:
<预><代码>>>>a = []>>>乙 = 一>>>a.append(9)>>>一种[9]>>>乙[9]>>>但是del
语句并没有达到同样的效果?
当你这样做时:
a = b
您所做的是将标签 b
分配给标签 a
所指的同一对象.
当你这样做时:
a.append(9)
您将 9
添加到 a
和 b
指向的列表对象中.这是同一个对象,所以它们显示相同的结果.
当你这样做时:
del a
您删除的是对象的引用,而不是对象本身.如果它是 only 引用,则对象将被垃圾回收.但是在您的情况下,还有另一个引用 - b
- 所以该对象继续存在.
Why does the following code change both variables:
>>> a = []
>>> b = a
>>> a.append(9)
>>> a
[9]
>>> b
[9]
>>>
But the del
statement does not achieve the same effect?
>>> a = []
>>> b = a
>>> del(a)
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> b
[]
>>>
When you do:
a = b
What you're doing is assigning the label b
to the same object that the label a
is refering to.
When you do:
a.append(9)
You're adding 9
to the list object pointed to by both a
and b
. It's the same object, so they show the same result.
When you do:
del a
You're deleting the reference to the object, not the object itself. If it's the only reference, then the object will be garbage collected. But in your case, there's another reference - b
- so the object continues to exist.
这篇关于为什么 del 不做同样的事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!