python中单例模式

python 复制代码
import threading





class Singleton(type):
    _instances = {}
    _instance_lock = threading.Lock()
    con = threading.Condition(_instance_lock)

    def __call__(cls, *args, **kwargs):
        key = '&&'.join([str(i) for i in args])
        if key not in cls._instances:
            if cls._instance_lock.locked():
                cls.con.wait()
            cls._instance_lock.acquire()
            cls._instances[key] = super(Singleton, cls).__call__(*args, **kwargs)
            cls._instance_lock.release()
            return cls._instances[key]
            
        else:
            return cls._instances[key]



class MyClass(metaclass=Singleton):
    
    def __init__(self,username):
        print(username)
        self.username = username
        
    def get_username(self):
        return self.username
    
a1 = MyClass("test")
print(a1.get_username())
a2 = MyClass("test")
print(a1.get_username())
    

debug可以发现,MyClass只实例化了一次

https://stackoverflow.com/questions/6760685/what-is-the-best-way-of-implementing-singleton-in-python

相关推荐
智能体与具身智能1 小时前
TVA具身智能的概念、架构与应用(19)
人工智能·python·具身智能
小灰灰搞电子2 小时前
Rust+Slint 实现动态消息提示框源码分享
开发语言·后端·rust
2601_962294612 小时前
python中range函数怎么用
python·for循环·可迭代对象·range函数·整数列表
传奇开心果编程3 小时前
【Rust入门知识点学与练】第21课:Trait 进阶 Advanced Traits
开发语言·学习·rust
青 春 记 忆3 小时前
零基础入门python70:Docker Compose 编排完整后端
python·后端开发
新时代牛马3 小时前
字符设备驱动完整篇:从 cdev_add、file_operations 到chrdev_open 与排障
开发语言·python
swordbob3 小时前
ReentrantLock 与 AQS 完整学习手册
java·开发语言
白山编程大哥4 小时前
Java OutputStreamWriter 详解:从字符到字节的桥梁
java·开发语言·python
落羽的落羽5 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Chasing__Dreams5 小时前
大模型应用开发--13--RAG 查询优化策略
python