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

相关推荐
夜雪一千2 小时前
Python enumerate() 函数完整详解:遍历同时获取索引,告别手动计数
服务器·windows·python
能有时光3 小时前
PyTorch KernelAgent 源码解读 ---(4)--- ExtractorAgent
人工智能·pytorch·python
_Jimmy_3 小时前
Python 协程库如何使用以及有哪些使用场景
python
aqi004 小时前
15天学会AI应用开发(十七)使用LangGraph实现会话记忆功能
人工智能·python·大模型·ai编程·ai应用
西门吹-禅4 小时前
java springboot N+1问题
java·开发语言·spring boot
第一程序员4 小时前
Rust Agent 子进程执行:Command 之前,先定义输入和超时
python·rust·github
skywalk81634 小时前
设计并实现段言的 C FFI 绑定机制 @Trae
c语言·开发语言·python·编程
weixin_BYSJ19874 小时前
SpringBoot + MySQL 乒乓球运动员信息管理系统项目实战--附源码04954
java·javascript·spring boot·python·django·flask·php
IT笔记6 小时前
【Rust】Rust Match 模式匹配详解
java·开发语言·rust
2zcode6 小时前
免费开源项目文档:基于MATLAB卷积神经网络的口罩佩戴检测系统
开发语言·matlab·cnn