zoukankan      html  css  js  c++  java
  • python __del__() 清空对象

    python __del__() 清空对象

    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
    =====================================
    销毁创建的对象
    =====================================
    循环中.......
    循环中.......
    循环中.......
    循环中.......
  • 相关阅读:
    PHP chop() 函数
    PHP bin2hex() 函数
    多个表关联或者有视图套视图,快速检查SQL语句中所有的表统计信息是否过期
    洛谷P3628 [APIO2010]特别行动队 斜率优化
    洛谷P3195 [HNOI2008]玩具装箱TOY 斜率优化
    bzoj4282 慎二的随机数列 树状数组求LIS + 构造
    校园网 入读统计 + 性质分析
    HAOI2006 受欢迎的牛 缩点
    普通平衡树 Treap
    洛谷P1563 玩具谜题 简单模拟
  • 原文地址:https://www.cnblogs.com/111testing/p/13986374.html
Copyright © 2011-2022 走看看