python - 让一个类对象从它的包含结构中移除自己
问题描述
我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 中的垃圾收集有点复杂,但实际上,当不再引用对象时,对象就会成为候选对象!
与其让对象从列表中删除自己,不如让调用者去做——如果这不能直接实现,请提供一个中间类来托管集合并进行任何需要的清理
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),但我相信删除对对象的所有引用最终会导致它从内存中删除。
推荐阅读
- html - 如何从引导手风琴中删除底部边框
- javascript - 如何在Javascript中检查函数的返回值是否未定义
- deep-learning - 训练和验证精度高,但无法正确预测单个图像
- python - 如何为aws lambda python代码设置时间戳到aws区域时区
- python - 来自字符串的Python Flask“make_response”
- reactjs - 开玩笑要定义多个属性
- google-apps-script - 如何计算新的 Google 工作表链接
- javascript - 关于将文档增量添加到 Firestore React Native
- android - 无法解析主机。没有与主机名关联的地址
- python - 将时间序列值转换为 python 列表