How do I correctly clean up a Python object?

后端 未结 10 1159
北荒
北荒 2020-11-22 16:59
class Package:
    def __init__(self):
        self.files = []

    # ...

    def __del__(self):
        for file in self.files:
            os.unlink(file)
         


        
10条回答
  •  星月不相逢
    2020-11-22 17:30

    atexit.register is the standard way as has already been mentioned in ostrakach's answer.

    However, it must be noted that the order in which objects might get deleted cannot be relied upon as shown in example below.

    import atexit
    
    class A(object):
    
        def __init__(self, val):
            self.val = val
            atexit.register(self.hello)
    
        def hello(self):
            print(self.val)
    
    
    def hello2():
        a = A(10)
    
    hello2()    
    a = A(20)
    

    Here, order seems legitimate in terms of reverse of the order in which objects were created as program gives output as :

    20
    10
    

    However when, in a larger program, python's garbage collection kicks in object which is out of it's lifetime would get destructed first.

提交回复
热议问题