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
    =====================================
    销毁创建的对象
    =====================================
    循环中.......
    循环中.......
    循环中.......
    循环中.......
  • 相关阅读:
    sql server 函数的自定义
    MVC View小技巧
    存储过程实例《转载》
    用递归方法求n!
    八皇后问题之我的理解
    蓝桥杯:排它平方数-java
    谷歌统计使用代码部署和事件API使用
    网站自动登录功能的设计
    通过js来设置cookie和读取cookie,实现登陆时记住密码的功能
    QQ互联第三方登陆 redirect uri is illegal(100010)
  • 原文地址:https://www.cnblogs.com/111testing/p/13986374.html
Copyright © 2011-2022 走看看