我试图了解CPython垃圾收集器的内部结构,特别是在调用析构函数时。到目前为止,这种行为是直观的,但以下案例却让我感到困惑:禁用GC。在
创建一个对象,然后删除对它的引用。在
对象将被销毁,并调用了方法。在
我以为只有启用了垃圾回收器才会发生这种情况。有人能解释一下为什么会这样吗?有没有办法推迟调用析构函数?在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。