为什么 del 不做同样的事情? [英] Why doesn't del do the same thing?

查看:30
本文介绍了为什么 del 不做同样的事情?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码改变了两个变量:

<预><代码>>>>a = []>>>乙 = 一>>>a.append(9)>>>一种[9]>>>乙[9]>>>

但是del语句并没有达到同样的效果?

<预><代码>>>>a = []>>>乙 = 一>>>删除(一)>>>一种回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中NameError: 名称 'a' 未定义>>>乙[]>>>

解决方案

当你这样做时:

a = b

您所做的是将标签 b 分配给标签 a 所指的同一对象.

当你这样做时:

a.append(9)

您将 9 添加到 ab 指向的列表对象中.这是同一个对象,所以它们显示相同的结果.

当你这样做时:

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屋!

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