参考计数

绝大多数 Python 内存管理都是通过引用计数来处理的。

每次引用对象(例如,分配给变量)时,其引用计数都会自动增加。当它被解除引用时(例如变量超出范围),其引用计数会自动减少。

当引用计数达到零时,立即销毁该对象并立即释放内存。因此,对于大多数情况,甚至不需要垃圾收集器。

>>> import gc; gc.disable()  # disable garbage collector
>>> class Track:
        def __init__(self):
            print("Initialized")
        def __del__(self):
            print("Destructed")
>>> def foo():
        Track()
        # destructed immediately since no longer has any references
        print("---")
        t = Track()
        # variable is referenced, so it's not destructed yet
        print("---")
        # variable is destructed when function exits
>>> foo()
Initialized
DestructedInitializedDestructed

进一步证明参考文献的概念:

>>> def bar():
        return Track()
>>> t = bar()
Initialized
>>> another_t = t  # assign another reference
>>> print("...")
...
>>> t = None          # not destructed yet - another_t still refers to it
>>> another_t = None  # final reference gone, object is destructed
Destructed