我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是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 list_item[4]
del dictionary["alpha"]
这两者显然都是有用的。其次,在局部变量上使用del使意图更加明确。比较:
del foo
to
foo = None
我知道在del foo的情况下,目的是从作用域中删除变量。foo = None是否这样做还不清楚。如果有人只是赋值foo = None,我可能会认为这是死代码。但我立刻就知道,编码del foo的人想要做什么。
显式使用"del"也是比将变量赋值为None更好的实践。如果你试图删除一个不存在的变量,你会得到一个运行时错误,但如果你试图将一个不存在的变量设置为None, Python会无声地将一个新变量设置为None,让你想要删除的变量留在原来的位置。所以del会帮助你尽早发现错误
有一次我不得不使用:
del serial
serial = None
因为只使用:
serial = None
没有及时释放串口,无法立即再次打开。 从这一课中,我了解到del的真正意思是:“现在就开始!然后等待直到它完成”这在很多情况下都很有用。当然,你可能有一个system.gc.del_this_and_wait_balbalba (obj)。
在以上回答的基础上补充几点: 德尔x
x的定义表示r -> o(一个引用r指向一个对象o),但del x改变的是r而不是o。这是一个对对象的引用(指针)的操作,而不是与x相关的对象。区分r和o是这里的关键。
It removes it from locals(). Removes it from globals() if x belongs there. Removes it from the stack frame (removes the reference physically from it, but the object itself resides in object pool and not in the stack frame). Removes it from the current scope. It is very useful to limit the span of definition of a local variable, which otherwise can cause problems. It is more about declaration of the name rather than definition of content. It affects where x belongs to, not where x points to. The only physical change in memory is this. For example if x is in a dictionary or list, it (as a reference) is removed from there(and not necessarily from the object pool). In this example, the dictionary it belongs is the stack frame (locals()), which overlaps with globals().
我发现在使用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无法跟上时,系统会疯狂地切换,这可能会导致脚本停止,而它在宽松的内存阈值下运行得非常流畅,从而在机器工作时留下了足够的空间来使用机器浏览和编码。