參考計數

絕大多數 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