It actually works. You're probably confused by the fact that the object isn't being destroyed when you think it is - it may be destroyed at a later moment. See the documentation for more details, note especially that del x
is not guaranteed to call x.__del__
.
In general you should not use __del__
if you haven't got good enough reason to do so (and I actually don't think you have), and reasons good enough are rare.
Cases where I found that the function is actually called is for example:
x = tA()
x = None # __del__ is called in my python
tA() # __del__ is called in my python
x = tA()
exit # __del__ is called in my python
x = tA()
del x # __del__ is NOT called in my python
As for making a thread sleep before it quits you'll need to put the sleep in the thread code (note that __del__
might run in any thread and when the thread has already terminated), for example:
class tA(Thread):
def run(self):
try:
do_your_stuff()
finally:
time.sleep(5)
note that finally
makes sure that time.sleep(5)
is called whether do_your_stuff()
returns sucessfully or raises exception.