how to achive - file write open on __del__?

后端 未结 4 528
予麋鹿
予麋鹿 2021-01-22 18:40

I m trying to do a some activity on class obj destruction. How do I achive file open in _del__ function? (I m using Python 3.4)

class iam(object):

    def __in         


        
4条回答
  •  一向
    一向 (楼主)
    2021-01-22 19:34

    Below code is work fine.

    class iam(object):
    
    def __init__(self):
        print("I m born")
    
    def __del__(self):
        #"open" function still in __builtins__ 
        f = open("memory_report.txt", "w")
        f.write("He gone safe")
        f.close()
    
    def write_iam():
            i=iam()
    
    if __name__ == '__main__':
        write_iam()
        print("Script Ends. Now to GC clean memory")
    

    In this case:

    class iam(object):
    
    def __init__(self):
        print("I m born")
    
    def __del__(self):
        #__builtins__.open  has remove 
        f = open("memory_report.txt", "w")
        f.write("He gone safe")
        f.close()
    
    if __name__ == '__main__':
        i = iam()
        print("Script Ends. Now to GC clean memory")
    

    When exit the __main__ function, before GC delete the "i" instance (execute i.__delete__) "open" function has remove from __builtins__.

提交回复
热议问题