CodeWalk

Python 中 __del__ 和垃圾回收

作者:我还是少年 · 2026-05-30 12:55

Python 中 __del__ 方法有什么作用?它和垃圾回收有什么关系?使用它有什么注意事项?

回答

我还是少年

__del__(self)析构方法,在对象被垃圾回收时调用,用于释放资源。

class Resource:
    def __init__(self):
        self.file = open('data.txt')

    def __del__(self):
        print('Cleaning up')
        self.file.close()

注意事项

  1. 调用时机不确定:GC 时间不可预测,不保证立即执行
  2. 循环引用:如果 __del__ 参与循环引用,对象变为 gc.garbage 无法回收
  3. 异常忽略__del__ 中的异常被忽略(打印 stderr)
  4. 全局变量约束__del__ 执行时模块可能已清理完毕
# 不依赖 __del__,使用上下文管理器
class Resource:
    def __init__(self):
        self.file = open('data.txt')
    def close(self):
        self.file.close()

# 推荐:使用 with 语句
with Resource() as r:
    pass

最佳实践:避免使用 __del__,用 with 和上下文管理器替代。