我真的想不出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删除变量及其所指向的对象的绑定。
>>> a = ['a', 'b', 'c']
>>> b = a
>>> del a
>>> b
['a', 'b', 'c']
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
我能想到的一个简单的用例是,如果你已经使用内置函数名作为变量,并且你想在它已经被你的变量名“覆盖”之后使用该函数。
t = ('a', "letter")
value, type = t
print(value, type)
del type
print(type(value))
输出:
a letter
<class 'str'>
只是另一种想法。
当在Django这样的框架中调试http应用程序时,调用堆栈中充满了以前使用过的无用和混乱的变量,特别是当它是一个非常长的列表时,这对开发人员来说是非常痛苦的。因此,在这一点上,名称空间控制可能是有用的。
del所做的部分(来自Python语言参考):
删除名称将从本地或全局名称空间删除该名称的绑定
将None赋值给名称不会删除名称与名称空间的绑定。
(我想关于移除名称绑定是否真的有用可能会有一些争论,但这是另一个问题。)
有一次我不得不使用:
del serial
serial = None
因为只使用:
serial = None
没有及时释放串口,无法立即再次打开。 从这一课中,我了解到del的真正意思是:“现在就开始!然后等待直到它完成”这在很多情况下都很有用。当然,你可能有一个system.gc.del_this_and_wait_balbalba (obj)。
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?