def singleton(cls): threadNames = [] # 线程名称列表 instances = {} # 实例字典 def get_instance(threadName, *args, **kwargs): """ 获取单例实例,通过线程名创建单例,保障每个线程里面的实例保持一致 参数: - threadName: 线程名称 返回: - instances[cls]: 单例实例 """ if threadName not in threadNames: # 如果线程名称不在线程名称列表中 instances[cls] = cls(threadName,*args) # 实例字典中存储类的实例 threadNames.append(threadName) # 将线程名称添加到线程名称列表中 return instances[cls] # 返回实例字典中存储的类的实例 return get_instance # 返回get_instance函数 @singleton class threadNameSingleton: def __init__(self,threadName,*args): print(f"{threadName} 单例创建成功") if __name__ == '__main__': pc1 = threadNameSingleton("pc1") pc11 = threadNameSingleton("pc1") # print(threadNames) pc2 = threadNameSingleton("pc2") pc22 = threadNameSingleton("pc2") # print(threadNames) print(id(pc1), id(pc11)) print(id(pc1), id(pc2)) print(id(pc2), id(pc22))