马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- 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
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |