Is __del__ really a destructor?

前端 未结 4 735
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 14:58

I do things mostly in C++, where the destructor method is really meant for destruction of an acquired resource. Recently I started with python (which is really a fun and fantast

相关标签:
4条回答
  • 2021-02-05 15:12

    So uncommon it is that I have learned about it today (and I'm long ago into python).

    Memory is deallocated, files closed, ... by the GC. But you could need to perform some task with effects outside of the class.

    My use case is about implementing some sort of RAII regarding some temporal directories. I'd like it to be removed no matter what.

    Instead of removing it after the processing (which, after some change, was no longer run) I've moved it to the __del__ method, and it works as expected.

    This is a very specific case, where we don't really care about when the method is called, as long as it's called before leaving the program. So, use with care.

    0 讨论(0)
  • 2021-02-05 15:15

    Is del really a destructor?

    No, __del__ method is not a destructor, is just a normal method you can call whenever you want to perform any operation, but it is always called before the garbage collector destroys the object. Think of it like a clean or last will method.

    0 讨论(0)
  • 2021-02-05 15:32

    In the Python 3 docs the developers have now made clear that destructor is in fact not the appropriate name for the method __del__.

    object.__del__(self)

    Called when the instance is about to be destroyed. This is also called a finalizer or (improperly) a destructor.

    Note that the OLD Python 3 docs used to suggest that 'destructor' was the proper name:

    object.__del__(self)

    Called when the instance is about to be destroyed. This is also called a destructor. If a base class has a __del__() method, the derived class’s __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance.

    From other answers but also from the Wikipedia:

    In a language with an automatic garbage collection mechanism, it would be difficult to deterministically ensure the invocation of a destructor, and hence these languages are generally considered unsuitable for RAII [Resource Acquisition Is Initialization]

    So you should almost never be implementing __del__, but it gives you the opportunity to do so in some (rare?) use cases

    0 讨论(0)
  • 2021-02-05 15:39

    As the other answers have already pointed out, you probably shouldn't implement __del__ in Python. If you find yourself in the situation thinking you'd really need a destructor (for example if your class wraps a resource that needs to be explicitly closed) then the Pythonic way to go is using context managers.

    0 讨论(0)
提交回复
热议问题