【python基础】weakref的初次遇见

我们先来看一段代码

python 复制代码
class DatabaseConnection:
    """模拟数据库连接"""

    def __init__(self, db_name):
        self.db_name = db_name
        print(f"连接到数据库 {db_name}")

    def __del__(self):
        print(f"关闭数据库连接 {self.db_name}")


cache = {}

cache["db1"] = DatabaseConnection("my_database")
print("删除 cache 中的 db1 前,cache 内容:", cache)
del cache["db1"]
print("删除 cache 中的 db1 后,cache 内容:", cache)
import gc
gc.collect()  # 手动触发垃圾回收
print("手动触发垃圾回收后,cache 内容:", cache)

print("-" * 50)

输出结果:

python 复制代码
连接到数据库 my_database

删除 cache 中的 db1 前,cache 内容: {'db1': <__main__.DatabaseConnection object at 0x7fb3cc333430>}

关闭数据库连接 my_database

删除 cache 中的 db1 后,cache 内容: {}

手动触发垃圾回收后,cache 内容: {}

​ 这是一个简易的数据库连接管理器。DatabaseConnection类,模拟了一个数据库的连接,字典cache存储数据库的连接对象,我们通过 del删除字典中的 db1条目,但python的回收机制是引用回收,cache字典仍然持有数据库连接对象的引用,因此对象的内存不会立即被释放,如果我们这次连接结束,如果后续不断创建新的数据库连接对象并添加到字典中,那这个字典会越来越大。这时候,我们需要手动的去触发回收垃圾,每次这样子清理非常的麻烦。 ​ 这时候我们就可以使用weakref(弱引用)来缓存数据库的连接,这样子数据库连接对象在没有其他强引用时被自动回收。

python 复制代码
import weakref

class DatabaseConnection:
    """模拟数据库连接"""

    def __init__(self, db_name):
        self.db_name = db_name
        print(f"连接到数据库 {db_name}")

    def __del__(self):
        print(f"关闭数据库连接 {self.db_name}")


cache = weakref.WeakValueDictionary()

db_connection = DatabaseConnection("my_database")
cache["db1"] = db_connection
print("删除 db_connection 前,cache 内容:", dict(cache))
del db_connection
print("删除 db_connection 后,cache 内容:", dict(cache))

输出结果:

python 复制代码
连接到数据库 my_database

删除 db_connection 前,cache 内容: {'db1': <__main__.DatabaseConnection object at 0x7fb3cdb8d2e0>}

关闭数据库连接 my_database

删除 db_connection 后,cache 内容: {}
python"""
相关推荐
开发者联盟league1 分钟前
pip install出现报错ERROR: Cannot set --home and --prefix together
开发语言·python·pip
Cloud_Shy6185 分钟前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(附录 C 高级 Python 概念)
python·数据分析·excel
隔壁大炮6 分钟前
MNE-Python 第2天学习笔记:Montage与通道信息管理
python·eeg·mne·脑电数据处理
涛声依旧-底层原理研究所14 分钟前
防止Agent胡来五大安全防线
人工智能·python
RSTJ_162516 分钟前
PYTHON+AI LLM DAY FIFITY-THREE
开发语言·人工智能·python
晚烛18 分钟前
CANN 模型蒸馏实战:大模型知识迁移到小模型
python·线性代数·矩阵
俊哥工具19 分钟前
解决网速卡顿、断网、网络报错,万能网络修复工具教程
网络·python·django·计算机外设·智能路由器·pygame
WL_Aurora20 分钟前
Python爬虫实战(九):百度百聘招聘数据采集
爬虫·python·百度
lili001221 分钟前
Gemini 3.5发布后的AI格局:谷歌重新定义行业标准
java·人工智能·python·ai编程
JunLa25 分钟前
Java语法糖
java·python·哈希算法