本文介绍了del 在 Python 中什么时候有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实在想不出 Python 需要 del 关键字的任何原因(而且大多数语言似乎没有类似的关键字).例如,与其删除一个变量,不如将 None 赋值给它.当从字典中删除时,可以添加一个del方法.

I can't really think of any reason why Python needs the del keyword (and most languages seem to not have a similar keyword). For instance, rather than deleting a variable, one could just assign None to it. And when deleting from a dictionary, a del method could be added.

是否有理由在 Python 中保留 del,还是 Python 前垃圾收集时代的遗迹?

Is there a reason to keep del in Python, or is it a vestige of Python's pre-garbage collection days?

推荐答案

首先,除了局部变量,你还可以删除其他东西

Firstly, you can del other things besides local variables

del list_item[4]
del dictionary["alpha"]

这两者都应该是非常有用的.其次,在局部变量上使用 del 使意图更清晰.比较:

Both of which should be clearly useful. Secondly, using del on a local variable makes the intent clearer. Compare:

del foo

foo = None

我知道在 del foo 的情况下,目的是从作用域中删除变量.目前尚不清楚 foo = None 是否正在这样做.如果有人只是分配了 foo = None,我可能会认为这是死代码.但我立刻知道编写del foo 代码的人想做什么.

I know in the case of del foo that the intent is to remove the variable from scope. It's not clear that foo = None is doing that. If somebody just assigned foo = None I might think it was dead code. But I instantly know what somebody who codes del foo was trying to do.

这篇关于del 在 Python 中什么时候有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 04:48