为什么不德尔做同样的事情? [英] Why doesn't del do the same thing?
问题描述
为什么以下code改变这两个变量:
>>>一个= []
>>> B = A
>>> a.append(9)
>>>一个
[9]
>>> b
[9]
>>>
但删除
语句没有达到同样的效果?
>>>一个= []
>>> B = A
>>>德尔(一)
>>>一个
回溯(最近通话最后一个):
文件<&标准输入GT;,1号线,上述<&模块GT;
NameError:名称'一'是没有定义
>>> b
[]
>>>
当你这样做:
A = B
你在做什么是分配标签 B
同一个对象的标签 A
是指的是
当你这样做:
a.append(9)
您要添加 9
到列表对象指向两个 A
和 b
。它是同一个对象,所以它们显示相同的结果。
当你这样做:
德尔一
您要删除的参考的对象,而不是对象本身。如果它是的只有的引用,那么对象将被垃圾收集。但是,在你的情况,还有另一种参考 - 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.
这篇关于为什么不德尔做同样的事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!