How do I correctly clean up a Python object?

后端 未结 10 1121
北荒
北荒 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:23

    The standard way is to use atexit.register:

    # package.py
    import atexit
    import os
    
    class Package:
        def __init__(self):
            self.files = []
            atexit.register(self.cleanup)
    
        def cleanup(self):
            print("Running cleanup...")
            for file in self.files:
                print("Unlinking file: {}".format(file))
                # os.unlink(file)
    

    But you should keep in mind that this will persist all created instances of Package until Python is terminated.

    Demo using the code above saved as package.py:

    $ python
    >>> from package import *
    >>> p = Package()
    >>> q = Package()
    >>> q.files = ['a', 'b', 'c']
    >>> quit()
    Running cleanup...
    Unlinking file: a
    Unlinking file: b
    Unlinking file: c
    Running cleanup...
    

提交回复
热议问题