>>> import gc
>>> gc.collect() # Force collection
Data.__del__
Data.__del__
如果循环引用的对象自己还定义了自己的 __del__() 方法,那么会让情况变得更糟糕。
# Node class involving a cycle
class Node:
def __init__(self):
self.data = Data()
self.parent = None
self.children = []
def add_child(self, child):
self.children.append(child)
child.parent = self
# NEVER DEFINE LIKE THIS.
# Only here to illustrate pathological behavior
def __del__(self):
del self.data
del.parent
del.children