zoukankan      html  css  js  c++  java
  • python基础----析构函数__del__

    析构方法,当对象在内存中被释放时,自动触发执行。

    注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的

    class Foo:
    
        def __del__(self):
            print('执行我啦')
    
    f1=Foo()
    del f1
    print('------->')
    
    #输出结果
    执行我啦
    ------->
    
    简单示范
    示例
    class Foo:
    
        def __del__(self):
            print('执行我啦')
    
    f1=Foo()
    # del f1
    print('------->')
    
    #输出结果
    ------->
    执行我啦
    
    
    
    
    
    #为何啊???
    
    挖坑埋了你
    示例(注意不一样的地方)

    笔记:

    import time
    class Open:
        def __init__(self,filepath,mode='r',encode='utf-8'):
            self.f=open(filepath,mode=mode,encoding=encode)
    
        def write(self):
            pass
    
        def __getattr__(self, item):
            return getattr(self.f,item)
    
        def __del__(self):
            print('----->del')
            self.f.close()
    
    f=Open('a.txt','w')
    f1=f
    del f
    
    print('=========>')
    View Code
  • 相关阅读:
    03-字典
    02-列表
    01-字符串操作
    Django中的跨域问题
    Codeforces Round #617 (Div. 3) A
    Codeforces Round #717 (Div. 2) A
    如何在Vuespa中使用less
    excle导出
    ajaxFileUpload上传文件
    图片插入word
  • 原文地址:https://www.cnblogs.com/wangyongsong/p/6763016.html
Copyright © 2011-2022 走看看