我有一个计时器类,我设计它触发一次,然后(最好)删除自身。有没有办法让我实现 self 删除?
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")
最佳答案
您可以遵循类似的方法。
可以调用object.__del__(self)
来销毁实例。
>>> class Test:
... def __del__(self):
... print "deleted"
...
>>> test = Test()
>>> del test
deleted
除非删除其所有引用,否则不会删除对象
此外,来自 Python 官方文档引用:
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
您的解决方案中需要的是使用类似 del object
的内容,其中该对象是您要删除的实例。
关于python - 如何在Python中销毁一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60842294/