def singleton(cls,*args,**kwargs): instances = {} def inner(cls,**kwargs): if cls not in instances: instances[cls] = cls(*args,**kwargs) return instances[cls] return inner@singletonclass Test1: pass# 推荐使用这种 简单好用 线程安全# ===========================================================import threadingclass Singleton: def __init__(self,cls): self.__cls = cls self.__instance = None self._lock = threading.Lock() def __call__(self,**kwargs): self._lock.acquire() if self.__instance is None: self.__instance = self.__cls(*args,**kwargs) self._lock.release() return self.__instance @Singletonclass Test2: pass# 继承时的执行顺序 base new -> son new -> son init. new 相当于构造方法,init相当于实例后再初始化 先执行父类的new 就好比先是人再是学生# ==============================================================class SingleBase(object): instance = None def __new__(cls,**kwargs): # if not instance: # instance = cls.__new__(*args,**kwargs): # return instance if cls.instance is None: cls.instance = object.__new__(cls) return cls.instance def __init__(self): passclass Test3(SingleBase): def __init__(self,name): self._name = name def get_name(self): return self._name# Meta 这个我还不是很懂# =====================================================class MetaSingleton(type): _instances = {} def __call__(cls,**kwargs): if cls not in cls._instances: cls._instances[cls] = super().__call__(*args,**kwargs) return cls._instances[cls]class Test4(Metaclass=MetaSingleton): def __init__(self): passif __name__ == '__main__': t1 = Test3('jwang') t2 = Test3('hello') print(ID(t1)) print(ID(t2)) print(t1.get_name()) print(t2.get_name()) test3 = Test4() test4 = Test4() print(ID(test3) == ID(test4))总结
以上是内存溢出为你收集整理的python singleton 4种单例全部内容,希望文章能够帮你解决python singleton 4种单例所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)