简体   繁体   中英

How do I destroy an object in python?

I have a timer class, that I designed to fire once, and (optimally) delete itself. Is there a way for me to implement that self-deletion?

class timer:
        def __init__(self, duration, function, args):
            self.duration = duration
            self.function = function
            self.args = args
        def start(self):
            self.time = time.time()
            self.validity = True    
        def check(self):
            if(int(self.time)+self.duration < time.time() ):
                self.function(self.args)
                self.validity = False
        def __del__(self):
            print("timer destroyed")

You can follow the similar approach.

An object.__del__(self) can be called to destroy an instance.

>>> class Test:
...     def __del__(self):
...         print "deleted"
... 
>>> test = Test()
>>> del test
deleted

Object is not deleted unless all of its references are removed

Also, From Python official doc reference:

del x doesn't directly call x. del () — the former decrements the reference count for x by one, and the latter is only called when x's reference count reaches zero

What you would need in your solution is to use something like del object where the object is the instance that you want to remove.

Did you try using None? something like this:

timer = None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM