我试图为每个队列创建单例实例。如果实例已经创建,它应该连接到相同的实例,或者创建一个新的实例。我已经使用队列来创建队列。
from queue import Queue
class Singleton(Queue):
__instance = None
def __new__(cls):
if cls.__instance is None:
cls.__instance = super().__new__(cls)
return cls.__instance
class Queue(object):
def __init__(self,**kwargs):
self.queue = Singleton
print(id(self.queue))
class Interpretor(object):
def __init__(self,**kwargs):
self.queue = Singleton
print(id(self.queue))
我得到相同的队列id为两个队列
2611032512096
2611032512096
要解决您的问题,您必须实现两个具有自己的类属性的单例。下面显示了一个示例(其中引用了一些线程,我在其中找到了对该解决方案的帮助):
from queue import Queue
class C_Queue(Queue):
__instance = None
def __new__(cls):
if cls.__instance is None:
cls.__instance = super().__new__(cls)
cls.__instance.__initialized = False
return cls.__instance
def __init__(self,**kwargs):
if self.__initialized:
return
self.initialized = True # To not call twice super().__init__()
super().__init__()
print('queue1')
class C_Interpretor(Queue):
__instance = None
def __new__(cls):
if cls.__instance is None:
cls.__instance = super().__new__(cls)
cls.__instance.__initialized = False
return cls.__instance
def __init__(self,**kwargs):
if self.__initialized:
return
self.initialized = True # To not call twice super().__init__()
super().__init__()
print('queue2')
if __name__ == '__main__':
q1 = C_Queue()
q1.put(item='hey_1')
q2 = C_Queue()
q2.put(item='hey_2')
i1 = C_Interpretor()
i2 = C_Interpretor()
print(id(q1))
print(id(q2))
print(q1.qsize()) # expected 2
print(id(i1))
print(id(i2))
更多信息可以在这里找到:
为什么是单例类'__init__()方法调用两次?
单例python调用两次__init__的问题