python - 如何在Python中销毁一个对象?

标签 python python-3.x python-3.7

我有一个计时器类,我设计它触发一次,然后(最好)删除自身。有没有办法让我实现 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/

相关文章:

python - Django 管理 css 丢失

python - 终止Python程序,但恢复数据

python - 无法导入类

python - 有效区分元组中不同可能的组合

python - 设置 python 3.7 虚拟环境时出现问题

python - 在 Tkinter GUI 中拖放文件

docker - 为什么打印不能与异步生成器一起正常工作?

python - 检查字典中的键是否定义

python-3.x - 在 Bokeh python 中创建雷达图的步骤是什么?

Python 3 [类型错误 : 'str' object cannot be interpreted as an integer] when working with sockets