问题描述
是否python垃圾回收器清理了一个复合对象,如果它的某些部分仍然被引用
eg
$ b由没有连接回它的原始容器。
请注意,这不是垃圾回收器, GC只处理打破循环引用。这个简单的例子完全由引用计数处理。
当 foo()返回时,本地名称空间被清除向上。这意味着 A 被删除,这意味着列表对象的引用计数将降为0.这将清除该列表对象,这意味着包含列表也是看他们的参考计数下降一个。对于 A [0] ,这意味着计数也会下降到0并被清除。
对于列表对象由 A [1] 引用,你现在有一个引用 B ,所以它的count仍然是1,仍然'活着'。
要确认相同的代码,只需使用 list 的子类和让我们知道何时该对象正在被删除:
>>> (自我)
...
> >> def foo():
... A = DelList([DelList([1,3,5,7]),DelList([2,4,6,8]))
.. 。return A [1]
...
>>> B = foo()
已删除[[1,3,5,7],[2,4,6,8]]
已删除[1,3,5,7]
> ;>>删除B
删除[2,4,6,8]
所有这些都是特定于CPython(参考Python实现);其他实现可能会以不同的方式处理对象生命周期(例如,使用垃圾收集器销毁扫描中的对象),但是 A 和 A [0] 在这些情况下不会改变; GC仍会收集其他实现中的那些,尽管也许在不同的时间点。
Does python garbage collector cleans up a compound object if some of its parts are still referenced
e.g.
def foo(): A = [ [1, 3, 5, 7], [2, 4, 6, 8]] return A[1] B = foo()Will A[0] be garbage collected?
Is there a way to confirm the same through code?
解决方案Nothing references the list A and the nested list A[0], so yes, they will be deleted from memory.
The nested list object referenced by A[1] has no connection back to its original container.
Note that it's not the garbage collector that does this; the GC only deals in breaking circular references. This simple case is handled entirely by reference counting.
The moment foo() returns, the local namespace is cleared up. That means A is removed, which means the list object reference count drops to 0. This clears that list object, which means that the contained lists also see their reference count drop by one. For A[0] that means the count drops to 0 too and it is cleared.
For the list object referenced by A[1], you now have a reference B to it, so it's count is still 1 and it remains 'alive'.
To confirm the same through code, simply use a subclass of list with a __del__ method to let us know when the object is being deleted:
>>> class DelList(list): ... def __del__(self): ... print 'Deleted {}'.format(self) ... >>> def foo(): ... A = DelList([DelList([1, 3, 5, 7]), DelList([2, 4, 6, 8])]) ... return A[1] ... >>> B = foo() Deleted [[1, 3, 5, 7], [2, 4, 6, 8]] Deleted [1, 3, 5, 7] >>> del B Deleted [2, 4, 6, 8]All this is specific to CPython (the reference Python implementation); other implementations may handle object lifetimes differently (e.g. do use a garbage collector to destroy objects in sweeps), but the lifetime of A and A[0] doesn't change in those cases; the GC will still collect those in other implementations, albeit at a different point in time perhaps.
这篇关于复杂对象上的python垃圾收集器行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!