0
import  time

class tA(obj):

    def __init__(self):
        pass

    def __del__(self):
        time.sleep(5)

I found that, when the class tA is destroyed, it did not delay for 5 seconds. Why? And how to add delay?

are there method's to make a thread sleep before it quits?

王王王
  • 127
  • 1
  • 10
  • 2
    [Don't use the `__del__` method](http://stackoverflow.com/a/2452895/2846140) – Vincent Jul 24 '15 at 09:15
  • 3
    What do you mean when the *class* is destroyed? `__del__` is called when *instances* are destroyed. What are you actually trying to achieve? – jonrsharpe Jul 24 '15 at 09:16
  • How do you try to delete your instance ? Using `del instance_of_tA` ? –  Jul 24 '15 at 09:22
  • I want to wait a thread running a little time, before closed by sys – 王王王 Jul 24 '15 at 10:11
  • 1
    @王王王 I think it would be better if you ask that question instead, there are method's to make a thread sleep before it quits - even in the case of exceptions raised in the thread. Probably there is a solution that better suits your needs. – skyking Jul 24 '15 at 10:14

2 Answers2

2

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.

skyking
  • 13,817
  • 1
  • 35
  • 57
-2
>>> import time
>>> class test():
...     def __init__(self):
...             print "a"
...             time.sleep(5)
...     def __del__(self):
...             print "b"
...
>>> a=test()
a
b
>>>

For example it's working. If need call "sleep" in the last function of class.

Kostia Skrypnyk
  • 560
  • 6
  • 13
  • First of all it behaves different from the OP's intention (since the sleep is at init time), second it does not behave the way you state. – skyking Jul 24 '15 at 09:32