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

相关推荐
段一凡-华北理工大学5 小时前
工业智能体:从Codex/Claude到项目实战~系列文章05:从“AI助手“到“工业智能体“:能力跃迁与落地范式
人工智能·python·claude·codex·工业智能体·高炉炼铁智能化
深蓝AI5 小时前
ContextVar 到线程池就丢了?asyncio.to_thread 和 run_in_executor 实测
python
岁月宁静6 小时前
什么是 Agent:从"会聊天"到"会做事"
人工智能·python
岁月宁静7 小时前
AI 应用开发工程师简历怎么写:HR 初筛、技术复筛、面试追问,三道关卡各看什么?
人工智能·python·面试
来让爷抱一个7 小时前
Python 异步里混用同步库,事件循环被卡住的全过程
开发语言·python
小肝一下9 小时前
3.基础语法(3)
python
深蓝AI10 小时前
Python 子进程树:父进程被杀后,孙进程为何还在跑?
python
心祭丫丫10 小时前
【每天一个 Python 小案例17】Python 实现通讯录
开发语言·人工智能·笔记·python·学习
爱你真是太好了10 小时前
Skill 索引瘦身与渐进加载
python
贾公子10 小时前
检测链路的容量规划——用 Little's Law 算清 QPS、并发与积压
后端·python