python
中的del比较特殊,因为python
都是引用,del
只是操作变量,而不是数据对象上
官方文档解释
The del statement
del_stmt ::= "del" target_list
Deletion is recursively defined very similar to the way assignment is defined. Rather than spelling it out in full details, here are some hints.
Deletion of a target list recursively deletes each target, from left to right.
Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised.
Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).
Changed in version 3.2: Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block
大概意思就是删除目标列表将从左到右递归删除每个目标,删除变量名称将从本地或者全局命名空间中移除该名称的绑定
下面举例说明下
例1
a=1 # 对象1 被变量a引用,对象1的引用计数器为1
b=a # 对象1 被变量b引用,对象1的引用计数器加1
c=a # 对象1 被变量c引用,对象1的引用计数器加1
del a #删除变量a,解除a对1的引用
del b #删除变量b,解除b对1的引用
print(c) #最终变量c仍然引用1
例2
li = [1, 2, 3, 4, 5] # 列表本身不包含数据1,2,3,4,5,而是包含变量:li[0] li[1] li[2] li[3] li[4]
first = li[0] # 拷贝列表数据,不会有数据对象的复制,而是创建新的变量引用
del li[0] # 删除li[0]对对象1的引用
print(li[0]) # 输出[2, 3, 4, 5]
print(first) # 输出
总结:
del
删除的只是变量,没有删除对变量的引用。