python学习 __del__方法

class Dog:
def del(self):
print(’----------英雄over---------’)
dog1 = Dog()
dog2 = dog1
del dog1 #硬链接,数据可以有多个名字,删除dog1,不会删除dog1的对象
del dog2
print(’======================’)
#当对象所有的调用均在该程序中删除时(即引用计数为0),则调用__del__,清空对象
#当程序结束时,仍然没有删除所有调用时(即引用计数不为0),系统自动清除内存,调用__del__

查看引用计数

import sys
#查看引用计数的方法 sys.getrefcount()
class T:
pass

t=T()
sys.getrefcount(t)
2
#因为getrefcount函数在也会引用一次对象,所以计算结果会比真实的引用次数多1

tt=t
tttt=tt
sys.getrefcount(t)
4
#增加多个引用时,可以算出该引用次数

#当删除 t 时
del t
sys.getrefcount(t)
Traceback (most recent call last):
File “<pyshell#20>”, line 1, in
sys.getrefcount(t)
NameError: name ‘t’ is not defined
#此时无法计算引用值,因为t的引用值已经删除

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值