python垃圾回收机制:当一个对象的引用被完全清空之后,就会调用__del__()方法来清空这个对象

当对象的引用没有被完全清空时,代码如下:

class C():
    def __init__(self):
        print('调用构造器创建对象')

    def __del__(self):
        print('销毁创建的对象')

c1 = C()
c2 = c1
c3 = c1

print('=====================================')
print(str(id(c1)) +' , '+ str(id(c2)) +' , '+ str(id(c3)))
print('=====================================')
del c1
del c2
# del c3      先保留c3,不完全删除C()的引用

# print(c1)   不注释的话会报错:NameError: name 'c1' is not defined
# print(c2)   不注释的话会报错:NameError: name 'c2' is not defined
print(c3)     #  输出:<__main__.C object at 0x0000023444AF0AC0>

print('=====================================')
while True:
    time.sleep(2)
    print('循环中.......')

输出结果: 下面的输出结果里面没有显示 “销毁创建的对象”

调用构造器创建对象
=====================================
2423513877184 , 2423513877184 , 2423513877184
=====================================
<__main__.C object at 0x0000023444AF0AC0>              
=====================================
循环中.......
循环中.......
循环中.......
循环中.......

 

当对象的引用完全被清空时,代码如下:

class C():
    def __init__(self):
        print('调用构造器创建对象')

    def __del__(self):
        print('销毁创建的对象')

c1 = C()
c2 = c1
c3 = c1

print('=====================================')
print(str(id(c1)) +' , '+ str(id(c2)) +' , '+ str(id(c3)))
print('=====================================')
del c1
del c2
del c3    #已经将对象的引用全部删除,程序会自动调用 __del__方法

# print(c1)     不注释的话会报错:NameError: name 'c1' is not defined
# print(c2)     不注释的话会报错:NameError: name 'c2' is not defined
# print(c3)     不注释的话会报错:NameError: name 'c3' is not defined

print('=====================================')
while True:
    time.sleep(2)
    print('循环中.......')

输出结果:

调用构造器创建对象
=====================================
2873013504704 , 2873013504704 , 2873013504704
=====================================
销毁创建的对象
=====================================
循环中.......
循环中.......
循环中.......
循环中.......

 

相关文章:

  • 2021-09-27
  • 2021-10-25
  • 2021-05-26
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-31
  • 2022-01-13
  • 2021-09-27
  • 2022-12-23
  • 2021-06-03
相关资源
相似解决方案