什么时候del在python中有用? [英] When is del useful in 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.
是否有任何理由将del
保留在python中,或者这是Python的垃圾收集日的痕迹?
Is there any 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中有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!