python单例模式

设计模式:单例模式(Singleton Pattern)。单例模式确保一个类只有一个实例,并提供一个全局访问点来获取这个实例。

python 复制代码
class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            # 这里可以添加初始化代码
        return cls._instance

# 使用Singleton类
instance1 = Singleton()
instance2 = Singleton()

# instance1 和 instance2 是同一个实例
assert instance1 is instance2

在这个例子中:

cls指的是类Singleton本身。

super().new (cls)调用父类(在这个例子中是object类)的__new__方法来创建类Singleton的一个新实例。这是因为__new__是在创建实例之前被调用的特殊方法,它实际上负责创建实例。

cls._instance用于存储这个唯一的实例。如果cls._instance已经存在,即之前已经创建过实例,那么__new__方法将返回这个已存在的实例而不是创建一个新的实例。

通过以上方式,无论你尝试创建多少次Singleton类的实例,所有的变量都会指向同一个实例。这就是单例模式的核心特点。
以上示例由ChatGPT生成

相关推荐
ZhengEnCi3 小时前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi4 小时前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽4 小时前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187915 小时前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L1 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅1 天前
海天线算法的前世今生
python·计算机视觉
韩师傅1 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L1 天前
LangGraph的MessageState and HumanMessage
python
韩师傅1 天前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L1 天前
python的类&继承
python