How do I correctly clean up a Python object?

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

    Here is a minimal working skeleton:

    class SkeletonFixture:
    
        def __init__(self):
            pass
    
        def __enter__(self):
            return self
    
        def __exit__(self, exc_type, exc_value, traceback):
            pass
    
        def method(self):
            pass
    
    
    with SkeletonFixture() as fixture:
        fixture.method()
    

    Important: return self


    If you're like me, and overlook the return self part (of Clint Miller's correct answer), you will be staring at this nonsense:

    Traceback (most recent call last):
      File "tests/simplestpossible.py", line 17, in                                                                                                                                                           
        fixture.method()                                                                                                                                                                                              
    AttributeError: 'NoneType' object has no attribute 'method'
    

    Hope it helps the next person.

提交回复
热议问题