how to achive - file write open on __del__?

后端 未结 4 529
予麋鹿
予麋鹿 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:16

    Below is an alternate I used - Using atexit handlers:

    import atexit
    
    
    class iam(object):
    
        def __init__(self):
            print("I m born")
            atexit.register(self.cleanup)
    
        def cleanup(self):
            f = open("memory_report.txt", "w")
            f.write("He gone safe")
            f.close()
            print ("Done")
    
    
    if __name__ == '__main__':
        i = iam()
        print("Script Ends. Now to GC clean memory")
    

    Output:

    I m born
    Script Ends. Now to GC clean memory
    Done
    

提交回复
热议问题