What is the __del__ method, How to call it?

后端 未结 5 2112
广开言路
广开言路 2020-11-22 05:28

I am reading a code. There is a class in which __del__ method is defined. I figured out that this method is used to destroy an instance of the class. However, I

5条回答
  •  时光取名叫无心
    2020-11-22 05:56

    The __del__ method, it will be called when the object is garbage collected. Note that it isn't necessarily guaranteed to be called though. The following code by itself won't necessarily do it:

    del obj
    

    The reason being that del just decrements the reference count by one. If something else has a reference to the object, __del__ won't get called.

    There are a few caveats to using __del__ though. Generally, they usually just aren't very useful. It sounds to me more like you want to use a close method or maybe a with statement.

    See the python documentation on __del__ methods.

    One other thing to note: __del__ methods can inhibit garbage collection if overused. In particular, a circular reference that has more than one object with a __del__ method won't get garbage collected. This is because the garbage collector doesn't know which one to call first. See the documentation on the gc module for more info.

提交回复
热议问题