首页 > 解决方案 > 让一个类对象从它的包含结构中移除自己

问题描述

class在实例化时将自定义 python 对象添加到列表中。我想让 pythonclass对象从列表中删除自己,并将自己从 ram 上运行的任何内存中删除,或者我基本上是在寻找class对象的析构函数和从 python 结构中删除实例的方法。我不拘泥于使用列表,并且愿意接受关于什么可能是更好的容器的建议,或者关于编码风格的任何其他建议。

我本质上要实现的错误伪代码示例:

mylist=[]
class myclass:
    def __init__(self,val):
        self.v=val
        print(self.v)
        mylist.append(self)

        # The following is what I'm looking for
        __superdestructor__(self):
        mylist.pop(self)
        memory.remove(self)

标签: python

解决方案


Python 中的垃圾收集有点复杂,但实际上,当不再引用对象时,对象就会成为候选对象!

与其让对象从列表中删除自己,不如让调用者去做——如果这不能直接实现,请提供一个中间类来托管集合并进行任何需要的清理

class MyBigClass():
    ...

class BigClassHolder():
    def __init__(self):
        self.container = list()  # put your objects in here

    ...  # some getting method
        return container.pop()  # only reference is now with the caller

还要考虑一个collections.deque关于线程安全和其他良好属性的列表!

还要注意,还有其他带有自己的垃圾收集器的 Python 实现(您可能使用第一个链接中引用的 CPython),但我相信删除对对象的所有引用最终会导致它从内存中删除。


推荐阅读