[英]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.可以调用
object.__del__(self)
来销毁实例。
>>> 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:另外,来自 Python 官方文档参考:
del x doesn't directly call x.
del x 不直接调用 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
del () — 前者将 x 的引用计数减一,后者仅在 x 的引用计数达到零时调用
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.您在解决方案中需要的是使用类似
del object
东西,其中对象是您要删除的实例。
Did you try using None?您是否尝试使用 None ? something like this:
像这样:
timer = None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.