我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
当前回答
del所做的部分(来自Python语言参考):
删除名称将从本地或全局名称空间删除该名称的绑定
将None赋值给名称不会删除名称与名称空间的绑定。
(我想关于移除名称绑定是否真的有用可能会有一些争论,但这是另一个问题。)
其他回答
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?
还有一个小众用途: 在带有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的更健全的对象管理能够填补这个空缺。
这是我贡献的2美分:
我有一个优化问题,我使用一个Nlopt库。 我初始化类和它的一些方法,我在代码的其他几个部分使用。
我得到的结果是随机的,即使是同样的数值问题。
我刚刚意识到,通过这样做,一些虚假数据包含在对象中,而它应该没有任何问题。使用del后,我猜内存被正确地清除,这可能是一个内部问题的类,其中一些变量可能不喜欢被重用没有适当的构造函数。
首先,你可以删除除局部变量之外的其他东西
del list_item[4]
del dictionary["alpha"]
这两者显然都是有用的。其次,在局部变量上使用del使意图更加明确。比较:
del foo
to
foo = None
我知道在del foo的情况下,目的是从作用域中删除变量。foo = None是否这样做还不清楚。如果有人只是赋值foo = None,我可能会认为这是死代码。但我立刻就知道,编码del foo的人想要做什么。
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 :)