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的引用值已经删除

猜你喜欢

转载自blog.csdn.net/IWTK_wcl/article/details/82988071
今日推荐