<p>因为<code>'BBB'</code>是用类的终结器(<code>__del__</code>函数)打印的。垃圾收集器收集对象时,将运行终结器和终结器。你知道吗</p>
<p>Python对垃圾收集使用双重策略:引用计数和循环检测。引用计数达到0的对象将被立即收集,但如果它们参与循环,则它们的计数将永远不会达到0。然后定期调用GC循环检测例程,最终将检测到它并释放所有悬空对象。你知道吗</p>
<p>在您的特定代码中,case#3创建了一个引用循环:<code>self.b</code>是对<code>self.func</code>的引用。但是GC循环检测永远不会运行,因为程序在有机会之前就结束了。你知道吗</p>
<p>但是,即使GC运行,带有终结器的对象也有特殊的规则。从<a href="https://docs.python.org/2/library/gc.html" rel="nofollow">documentation</a>:</p>
<blockquote>
<p><strong>Objects that have <code>__del__()</code> methods and are part of a reference cycle cause the entire reference cycle to be uncollectable</strong>, including objects not necessarily in the cycle but reachable only from it. Python doesn’t collect such cycles automatically because, in general, it isn’t possible for Python to guess a safe order in which to run the <code>__del__()</code> methods.</p>
</blockquote>
<p>另外,从<a href="https://docs.python.org/3/library/gc.html" rel="nofollow">here</a></p>
<blockquote>
<p>Changed in version 3.4: Following PEP 442, objects with a <code>__del__()</code> method don’t end up in <code>gc.garbage</code> anymore.</p>
</blockquote>
<p>因此,在3.4之前的Python中,在带有终结器的类中,您必须手动中断周期:</p>
<blockquote>
<p>If you know a safe order, you can force the issue by examining the garbage list, and explicitly breaking cycles due to your objects within the list. Note that these objects are kept alive even so by virtue of being in the garbage list, so they should be removed from garbage too. For example, after breaking cycles, do <code>del gc.garbage[:]</code> to empty the list.</p>
</blockquote>