我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
当前回答
首先,你可以删除除局部变量之外的其他东西
del list_item[4]
del dictionary["alpha"]
这两者显然都是有用的。其次,在局部变量上使用del使意图更加明确。比较:
del foo
to
foo = None
我知道在del foo的情况下,目的是从作用域中删除变量。foo = None是否这样做还不清楚。如果有人只是赋值foo = None,我可能会认为这是死代码。但我立刻就知道,编码del foo的人想要做什么。
其他回答
作为del可以用来做什么的例子,我发现它在这样的情况下很有用:
def f(a, b, c=3):
return '{} {} {}'.format(a, b, c)
def g(**kwargs):
if 'c' in kwargs and kwargs['c'] is None:
del kwargs['c']
return f(**kwargs)
# g(a=1, b=2, c=None) === '1 2 3'
# g(a=1, b=2) === '1 2 3'
# g(a=1, b=2, c=4) === '1 2 4'
这两个函数可以在不同的包/模块中,程序员不需要知道f中的参数c实际上有什么默认值。因此,通过将kwargs与del结合使用,您可以将其设置为None(或者在这种情况下也可以保留它),从而说“I want the default value on c”。
你也可以这样做:
def g(a, b, c=None):
kwargs = {'a': a,
'b': b}
if c is not None:
kwargs['c'] = c
return f(**kwargs)
然而,我发现前面的例子更加DRY和优雅。
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?
除非重新初始化,否则Del将从当前作用域删除变量。将其设置为None将其保留在当前范围内。
a = "python string"
print(a)
del a
print(a)
a = "new python string"
print(a)
输出:
python string
Traceback (most recent call last):
File "testing.py", line 4, in <module>
print(a)
NameError: name 'a' is not defined
我发现del有用的一个地方是清除for循环中的无关变量:
for x in some_list:
do(x)
del x
现在你可以确定,如果你在for循环之外使用x,它将是没有定义的。
只是另一种想法。
当在Django这样的框架中调试http应用程序时,调用堆栈中充满了以前使用过的无用和混乱的变量,特别是当它是一个非常长的列表时,这对开发人员来说是非常痛苦的。因此,在这一点上,名称空间控制可能是有用的。