我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
当前回答
我想详细说明公认的答案,以强调将变量设置为None与使用del删除变量之间的细微差别:
给定变量foo = 'bar',函数定义如下:
def test_var(var):
if var:
print('variable tested true')
else:
print('variable tested false')
一旦初始声明,test_var(foo)产生的变量测试为true。
现在试一试:
foo = None
test_var(foo)
它产生的变量测试为假。
将这种行为与以下行为进行对比:
del foo
test_var(foo)
现在会引发NameError: name 'foo'没有定义。
其他回答
还有一个小众用途: 在带有ROOT5或ROOT6的pyroot中,"del"可以用于删除引用不再存在的c++对象的python对象。这允许pyroot的动态查找找到同名的c++对象,并将其绑定到python名称。所以你可以有这样一个场景:
import ROOT as R
input_file = R.TFile('inputs/___my_file_name___.root')
tree = input_file.Get('r')
tree.Draw('hy>>hh(10,0,5)')
R.gPad.Close()
R.hy # shows that hy is still available. It can even be redrawn at this stage.
tree.Draw('hy>>hh(3,0,3)') # overwrites the C++ object in ROOT's namespace
R.hy # shows that R.hy is None, since the C++ object it pointed to is gone
del R.hy
R.hy # now finds the new C++ object
希望ROOT7的更健全的对象管理能够填补这个空缺。
我发现在使用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无法跟上时,系统会疯狂地切换,这可能会导致脚本停止,而它在宽松的内存阈值下运行得非常流畅,从而在机器工作时留下了足够的空间来使用机器浏览和编码。
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 serial
serial = None
因为只使用:
serial = None
没有及时释放串口,无法立即再次打开。 从这一课中,我了解到del的真正意思是:“现在就开始!然后等待直到它完成”这在很多情况下都很有用。当然,你可能有一个system.gc.del_this_and_wait_balbalba (obj)。
我发现del有用的一个地方是清除for循环中的无关变量:
for x in some_list:
do(x)
del x
现在你可以确定,如果你在for循环之外使用x,它将是没有定义的。