我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
当前回答
del is the equivalent of "unset" in many languages and as a cross reference point moving from another language to python.. people tend to look for commands that do the same thing that they used to do in their first language... also setting a var to "" or none doesn't really remove the var from scope..it just empties its value the name of the var itself would still be stored in memory...why?!? in a memory intensive script..keeping trash behind its just a no no and anyways...every language out there has some form of an "unset/delete" var function..why not python?
其他回答
I think one of the reasons that del has its own syntax is that replacing it with a function might be hard in certain cases given it operates on the binding or variable and not the value it references. Thus if a function version of del were to be created a context would need to be passed in. del foo would need to become globals().remove('foo') or locals().remove('foo') which gets messy and less readable. Still I say getting rid of del would be good given its seemingly rare use. But removing language features/flaws can be painful. Maybe python 4 will remove it :)
我发现del有用的一个地方是清除for循环中的无关变量:
for x in some_list:
do(x)
del x
现在你可以确定,如果你在for循环之外使用x,它将是没有定义的。
删除变量与将其设置为None不同
使用del删除变量名可能很少使用,但如果没有关键字,这是无法实现的。如果你可以通过写a=1来创建一个变量名,那么理论上你可以通过删除a来撤销这一点。
在某些情况下,它可以使调试更容易,因为试图访问已删除的变量将引发NameError。
可以删除类实例属性
Python允许你编写如下代码:
class A(object):
def set_a(self, a):
self.a=a
a=A()
a.set_a(3)
if hasattr(a, "a"):
print("Hallo")
如果选择向类实例动态添加属性,当然希望能够通过写入来撤销它
del a.a
首先,你可以删除除局部变量之外的其他东西
del list_item[4]
del dictionary["alpha"]
这两者显然都是有用的。其次,在局部变量上使用del使意图更加明确。比较:
del foo
to
foo = None
我知道在del foo的情况下,目的是从作用域中删除变量。foo = None是否这样做还不清楚。如果有人只是赋值foo = None,我可能会认为这是死代码。但我立刻就知道,编码del foo的人想要做什么。
Del经常出现在__init__.py文件中。任何在__init__.py文件中定义的全局变量都将自动“导出”(它将包含在from模块import *中)。避免这种情况的一种方法是定义__all__,但这可能会很混乱,并不是每个人都使用它。
例如,如果你在__init__.py中有这样的代码
import sys
if sys.version_info < (3,):
print("Python 2 not supported")
然后您的模块将导出sys名称。你应该写
import sys
if sys.version_info < (3,):
print("Python 2 not supported")
del sys