自学内容网 自学内容网

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


原文地址:https://blog.csdn.net/weixin_43632687/article/details/145285282

免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!