how to achive - file write open on __del__?

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

    The problem is, as MuSheng tried to explain, that the __builtins__ are removed before your __del__ is called.

    You can trigger the __del__ yourself by assigning None to the variable.

    MuSheng's code could be this:

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

    MuSheng deserves some upvotes, IMO

提交回复
热议问题