我真的想不出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?

其他回答

我发现在使用Numpy处理大数据时,del对于伪手动内存管理非常有用。例如:

for image_name in large_image_set:
    large_image = io.imread(image_name)
    height, width, depth = large_image.shape
    large_mask = np.all(large_image == <some_condition>)
    # Clear memory, make space
    del large_image; gc.collect()

    large_processed_image = np.zeros((height, width, depth))
    large_processed_image[large_mask] = (new_value)
    io.imsave("processed_image.png", large_processed_image)

    # Clear memory, make space
    del large_mask, large_processed_image; gc.collect()

当Python GC无法跟上时,系统会疯狂地切换,这可能会导致脚本停止,而它在宽松的内存阈值下运行得非常流畅,从而在机器工作时留下了足够的空间来使用机器浏览和编码。

删除变量与将其设置为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 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"命令对于控制数组中的数据非常有用,例如:

elements = ["A", "B", "C", "D"]
# Remove first element.
del elements[:1]
print(elements)

输出:

[' b ', ' c ', ' d ']

另一个小众案例,但很有用。

from getpass import getpass

pass = getpass()
token = get_auth_token(pass)
del pass

# Assume more code here...

在删除pass变量之后,您不会冒它稍后被错误打印出来的风险,或者以其他方式结束在日志或堆栈跟踪中。