41.__del__ 方法

例子一:

class B:
    def __del__(self):
        print(”内存被释放“)
 

b1 = B()
b2 = b1

print("hello world")

结果:

hello world  #先打印
--------i am over------   #后打印

上面例子说明,程序结束时,python解释器会自动调用del方法
不管是手动调用del还是由python自动回收都会触发del方法执行

例子二:

class B:
    def __del__(self):
        print("--------i am over------")
b1 = B()
del b1

print("hello world")

结果:

--------i am over------
hello world

删除b1的时候,对象的引用计数器由1变为0,调用了del方法

例子三:

class B:
    def __del__(self):
        print("--------i am over------")

b1 = B()
b2 = b1
del b1
print("hello world")

结果:

hello world #先
--------i am over------  #后

b1 与 b2 都指向该内存对象,引用计数器为2,但是只删除了b1,所以引用计数变为1
最后程序结束,自动调用del 方法

例子四:

class B:
    def __del__(self):
        print("--------i am over------")

b1 = B()
b2 = b1
del b1
del b2
print("hello world")

结果:

--------i am over------
hello world

删除b1与b2,引用计数器归0

如何查看引用计数器数量

import sys

class B:
    def __del__(self):
        print("--------i am over------")

b1 = B()
print(sys.getrefcount(b1))  #2 
b2 = b1

print(sys.getrefcount(b1))  #3
print(sys.getrefcount(b2))  #3 

del b1
print(sys.getrefcount(b2))  #2 
del b2

print("hello world")

使用sys.getrefcount() 方法来获取引用计数器的值,但该值会默认+1

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • http://python.jobbole.com/85231/ 关于专业技能写完项目接着写写一名3年工作经验的J...
    燕京博士阅读 7,632评论 1 118
  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 4,250评论 4 16
  • 文/山海风 谨以此连载小说献给那段青涩唯美的年少岁月,愿一切安好...
    烟台山海风阅读 323评论 1 1
  • 娘去世17年了,每每想起总是不能自已,即使是看到那些老太太也会想起娘,想起娘站在春风里目送我上学的情景,晨风吹动她...
    长跑人阅读 403评论 0 0
  • 文\孤岛沧月 昨天看了新上映的电影《大护法》,今天又心血来潮二刷了《一条狗的使命》,感慨良多,多日不动的笔杆子也少...
    琳咂酱阅读 519评论 3 3