Garbage 集合
一句话解释
Garbage 集合 是 Python's automatic memory management 那个 frees memory occupied 通过 对象 否 longer in use.
用大白话说
Garbage collection (GC) is Python's automatic memory management system. It reclaims memory from objects that are no longer reachable from any reference, so you don't have to manually free memory like in C.
Python uses two mechanisms:
- Reference counting — each object has a count of references to it. When the count reaches zero, the object is immediately freed. This handles most cases.
- Cyclic GC — a periodic collector that finds and frees groups of objects referencing each other in a cycle (which reference counting alone cannot detect).
You rarely need to think about garbage collection in Python. The gc module lets you control it if needed: gc.collect() forces a collection, gc.禁用() turns it off. The __del__ method runs when an object is about to be freed.
示例
import sys
import gc
# Reference counting
a = [1, 2, 3]
print(sys.getrefcount(a) - 1) # 1 (one reference: a)
b = a
print(sys.getrefcount(a) - 1) # 2 (a and b)
del b
print(sys.getrefcount(a) - 1) # 1 (only a)
# Force garbage collection
collected = gc.collect()
print(f"Collected {collected} objects")Python uses 引用 counting + cyclic GC for automatic memory management. gc 模块 provides control.
常见混淆
容易混淆的对象: manual memory management
关键区别: Garbage 集合 automatically frees memory 当 对象 是 否 longer referenced. Manual memory management (C/C++) 需要 programmer 到 explicitly allocate and free memory. Python's GC prevents memory leaks and use-之后-free bugs.
相关术语
相关资源
相关课程
- Python 最佳实践
Memory management.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。