There are many special methods in Python similar to __del__(self). Some of them, such as __gt__(), __le__(), etc., can guess their approximate functions from their names, but some cannot be guessed at will (of course Maybe it’s just me), for example, the __del__() and del that are about to appear here. I used to think that when del an object, __del__() will be called, but after failing the written test again and again , I just started to review these more subtle points ^_^!
Enough chatter and get to the point!
We know that del deletes an object. In fact, to be precise, it should decrease the reference count of the object by one. But note that __del__() will not be called every time it is called, because __del__() will be called when the reference count of the object drops to 0, as evidenced by the example:
>>> class C: def __del__(self): print("I'm vanishing...") >>> c = C() >>> b = c # 注意,此时对C()的引用计数为2 >>> del b >>> # 瞧,什么输出都没有,说明__del__()并没调用 >>> del c I'm vanishing... # 引用计数降为0后才被调用 >>>