处理带有循环引用的对象
我的设计如下:
__main__
引用a
a
引用b
b
引用 < code>aa
被创建,然后从__main__
中释放,
因此 a
和 b
具有循环参考。然而,在 del a
后,我更希望将 a
和 b
都处理掉。
我在很多地方看到使用上下文管理器的建议,特别是使用 with
语句而不是 __del__()
。然而,我看到的所有 with
示例都在本地范围内开始和结束(例如某个方法),
这可以用 with
优雅地执行吗?
还有什么选择呢?
My design is as follows:
__main__
referencesa
a
referencesb
b
referencesa
a
is created and then disposed of from__main__
Thus a
and b
have circular references. However upon del a
I would prefer both a
and b
disposed of.
I see in many places advice to use Context Managers, and specifically the with
statement instead of __del__()
. However all the examples I see of with
start and end in local scope (e.g. of a certain method)
Can this be elegantly performed with with
?
What is the alternative?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议:
__del__
中,而是在您在正确的时间调用的显式dispose
方法中。一般来说,当你知道你有循环引用,依赖于自动
__del__
处置不是一个好主意。它很脆弱——即使你设法让它在某些情况下工作,依赖项的微小变化也可能会再次破坏它。I recommend either:
__del__
but in an explicitdispose
method you call at the right time(s)In general, when you know you have circular references, relying on automatic
__del__
disposal is not a good idea. It's brittle - even if you manage to make it work in some case, small changes in dependencies can break it again.什么也不做。直到您创建数百万个这样的循环引用 - 并且可以证明这个(并且只有这个)正在破坏您的程序 - 实际上并不重要。
Do nothing. Until you create millions of circular references like this -- and can prove that this (and only this) is breaking your program -- it doesn't actually matter.
垃圾收集器应该处理这个问题。
Garbage collector is supposed to handle this.