关于Python中的del的一点思考

Python代码:
class ListNode:
    def __init__(self,x):
        self.x = x
        self.next = None
                
if __name__ == "__main__":
    p = ListNode(1)
    q = ListNode(2)
    p.next = q
    
    del q
    
    print p.next.x   //2

C++代码

#include <iostream>
using namespace std;

struct Node{
	int x;
	Node* next;
};

int main() {

	Node* p = new Node();
	p->x = 1;

	Node* q = new Node();
	q->x = 2;

	p->next = q;

	delete q;

	cout<<p->next->x<<endl;      //0

	return 0;
}
由上面的代码可知,python中的del跟C++中的delete是不一样的,del不会无条件的清掉变量所指向对象的内存。

del 〈 object ,...〉
Each object is any kind of Python object. Usually these are variables, but they can be functions, modules, classes.
The del statement works by unbinding the name, removing it from the set of names known to the Python interpreter. If this variable was the last remaining reference to an object, the object will be removed from memory. If, on the other hand, other variables still refer to this object, the object won't be deleted.

The del statement is typically used only in rare, specialized cases. Ordinary namespace management and garbage collection are generally sufficient for most purposes.


参考:

The del Statement

When is del useful in python?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值