我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
当前回答
在以上回答的基础上补充几点: 德尔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().
其他回答
有一次我不得不使用:
del serial
serial = None
因为只使用:
serial = None
没有及时释放串口,无法立即再次打开。 从这一课中,我了解到del的真正意思是:“现在就开始!然后等待直到它完成”这在很多情况下都很有用。当然,你可能有一个system.gc.del_this_and_wait_balbalba (obj)。
还有一个小众用途: 在带有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的更健全的对象管理能够填补这个空缺。
由于我还没有看到交互式控制台的答案,我将展示一个。
当foo=None时,该引用和对象存在,它不指向它。
而del foo也会销毁对象和引用。
如果你这样做如果foo是None并且它被删除了它就会升起NameError作为引用,它的对象所有介于两者之间的东西都会被del删除
删除目标列表会递归地从左到右删除每个目标。
与此同时,foo=None只是一个指向None的引用,因此引用仍然是有效的,对象也是如此。
[…在Python中,变量是对象的引用,任何变量都可以引用任何对象[…]
链接到引用1
链接到引用2
首先,你可以删除除局部变量之外的其他东西
del list_item[4]
del dictionary["alpha"]
这两者显然都是有用的。其次,在局部变量上使用del使意图更加明确。比较:
del foo
to
foo = None
我知道在del foo的情况下,目的是从作用域中删除变量。foo = None是否这样做还不清楚。如果有人只是赋值foo = None,我可能会认为这是死代码。但我立刻就知道,编码del foo的人想要做什么。
删除变量与将其设置为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