我试图了解 CPython 垃圾收集器的内部结构,特别是在调用析构函数时。到目前为止,这种行为是直观的,但下面的案例让我感到困惑:
- 禁用 GC。
- 创建一个对象,然后删除对它的引用。
- 对象被销毁并调用_____del_____ 方法。
我认为只有启用垃圾收集器才会发生这种情况。有人可以解释为什么会这样吗?有没有办法推迟调用析构函数?
import gc
import unittest
_destroyed = False
class MyClass(object):
def __del__(self):
global _destroyed
_destroyed = True
class GarbageCollectionTest(unittest.TestCase):
def testExplicitGarbageCollection(self):
gc.disable()
ref = MyClass()
ref = None
# The next test fails.
# The object is automatically destroyed even with the collector turned off.
self.assertFalse(_destroyed)
gc.collect()
self.assertTrue(_destroyed)
if __name__=='__main__':
unittest.main()
免责声明:此代码不适用于生产——我已经注意到这是非常特定于实现的,并且不适用于 Jython。