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
    =====================================
    销毁创建的对象
    =====================================
    循环中.......
    循环中.......
    循环中.......
    循环中.......
  • 相关阅读:
    JS中的timestamp
    HTML5之sessionStorage
    python之打包相关
    ls常用选项总结
    抓取网页内容生成kindle电子书
    在Py文件中引入django环境
    ACL
    Oracle 中的 Incarnation 到底是个什么?实验操作篇
    Oracle 中的 Incarnation 到底是个什么?概念理解篇
    OERR: ORA-32004 "obsolete or deprecated parameter(s) specified for %s instance"
  • 原文地址:https://www.cnblogs.com/111testing/p/13986374.html
Copyright © 2011-2022 走看看