类的定义如下:
class IterRegistry(type):
def __iter__(cls):
return iter(cls._registry)
class Example:
__metaclass__ = IterRegistry
_registry =[]
def __init__(self,iD):
self.iD = iD
self.count = 40
self._registry.append(self)
def reduceCount(self):
self.count -= 1
在程序的过程中,越来越多的类实例被创建。我有一个正在运行的计时器,然后它对所有实例运行 for 循环,并将每个实例的计数减 1。
def timer():
for i in Example:
i.reduceCount()
if i.count < 0:
#then delete the instance
我的问题是如何删除该实例?
最佳答案
您可以使用a del
statement .
del can also be used to delete entire variables:
>>> del a
Referencing the name a hereafter is an error (at least until another value is assigned to it).
但归根结底,这只是给垃圾收集器的一个建议。对象可能会立即被删除,但也可能在执行此语句后很久才被删除。它不受语言规范的保证。
关于python - 在Python中删除对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40205571/