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 天前
Java泛型擦除:原理、实践与应对策略
java·开发语言·人工智能·企业开发·发展趋势·技术原理
专注_每天进步一点点1 天前
【java开发】写接口文档的札记
java·开发语言
代码方舟1 天前
Java企业级实战:对接天远名下车辆数量查询API构建自动化风控中台
java·大数据·开发语言·自动化
flysh051 天前
C# 中类型转换与模式匹配核心概念
开发语言·c#
AC赳赳老秦1 天前
Python 爬虫进阶:DeepSeek 优化反爬策略与动态数据解析逻辑
开发语言·hadoop·spring boot·爬虫·python·postgresql·deepseek
浩瀚之水_csdn1 天前
Python 三元运算符详解
开发语言·python
源代码•宸1 天前
GoLang八股(Go语言基础)
开发语言·后端·golang·map·defer·recover·panic
Yuner20001 天前
Python机器学习:从入门到精通
python
rit84324991 天前
基于MATLAB的SUSAN特征检测算子边缘提取实现
开发语言·matlab
g***55751 天前
Java高级开发进阶教程之系列
java·开发语言