【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"""
相关推荐
zl21878654482 小时前
Playwright同步、异步、并行、串行执行效率比较
开发语言·python·测试工具
larance2 小时前
asyncio数据流
python
eqwaak03 小时前
Flask实战指南:从基础到高阶的完整开发流程
开发语言·后端·python·学习·flask
闲人编程5 小时前
深入理解Python的`if __name__ == ‘__main__‘`:它到底做了什么?
服务器·数据库·python·main·name·魔法语句
毕设源码-郭学长6 小时前
【开题答辩全过程】以 Python基于大数据的四川旅游景点数据分析与可视化为例,包含答辩的问题和答案
大数据·python·数据分析
Lin_Aries_04216 小时前
容器化 Flask 应用程序
linux·后端·python·docker·容器·flask
MediaTea6 小时前
Jupyter Notebook:基于 Web 的交互式编程环境
前端·ide·人工智能·python·jupyter
阿_旭6 小时前
基于深度学习的CT扫描图像肝脏肿瘤智能检测与分析系统【python源码+Pyqt5界面+数据集+训练代码】
人工智能·python·深度学习·肝脏肿瘤分割
belldeep7 小时前
python:Django 和 Vue.js 技术栈解析
vue.js·python·django