我实在想不出为什么Python需要del
关键字(而且大多数语言似乎都没有类似的关键字).例如,无需删除变量,只需将None
赋给它即可.当从字典中删除时,可以添加del
方法.
在Python中保留del
是有原因的吗,还是它是Python在垃圾收集之前的遗迹?
我实在想不出为什么Python需要del
关键字(而且大多数语言似乎都没有类似的关键字).例如,无需删除变量,只需将None
赋给它即可.当从字典中删除时,可以添加del
方法.
在Python中保留del
是有原因的吗,还是它是Python在垃圾收集之前的遗迹?
首先,你可以删除除局部变量之外的其他东西
del list_item[4]
del dictionary["alpha"]
这两种方法显然都很有用.其次,在局部变量上使用del
可以让意图更清晰.比较:
del foo
至
foo = None
I know in the case of del foo
that the intent is 至 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 至 do.