我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
我真的想不出Python需要del关键字的任何原因(而且大多数语言似乎都没有类似的关键字)。例如,与其删除变量,还不如将None赋值给它。当从字典中删除时,可以添加del方法。
在Python中保留del是有原因的吗,还是它是Python前垃圾收集时代的遗迹?
当前回答
Del经常出现在__init__.py文件中。任何在__init__.py文件中定义的全局变量都将自动“导出”(它将包含在from模块import *中)。避免这种情况的一种方法是定义__all__,但这可能会很混乱,并不是每个人都使用它。
例如,如果你在__init__.py中有这样的代码
import sys
if sys.version_info < (3,):
print("Python 2 not supported")
然后您的模块将导出sys名称。你应该写
import sys
if sys.version_info < (3,):
print("Python 2 not supported")
del sys
其他回答
Del经常出现在__init__.py文件中。任何在__init__.py文件中定义的全局变量都将自动“导出”(它将包含在from模块import *中)。避免这种情况的一种方法是定义__all__,但这可能会很混乱,并不是每个人都使用它。
例如,如果你在__init__.py中有这样的代码
import sys
if sys.version_info < (3,):
print("Python 2 not supported")
然后您的模块将导出sys名称。你应该写
import sys
if sys.version_info < (3,):
print("Python 2 not supported")
del sys
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'>
del所做的部分(来自Python语言参考):
删除名称将从本地或全局名称空间删除该名称的绑定
将None赋值给名称不会删除名称与名称空间的绑定。
(我想关于移除名称绑定是否真的有用可能会有一些争论,但这是另一个问题。)
另一个小众案例,但很有用。
from getpass import getpass
pass = getpass()
token = get_auth_token(pass)
del pass
# Assume more code here...
在删除pass变量之后,您不会冒它稍后被错误打印出来的风险,或者以其他方式结束在日志或堆栈跟踪中。
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?