分享两种 Python 中的单例模式
中心思想 : 在实例之前判断 该类的属性有没有被实例化过。 如果没有就实例话, 有的话就返回上一次实例话
第一种: 通过 python 自带的 __new__ 去实现
import threading class Singleton(object): _instance_lock = threading.Lock() def __init__(self): pass def __new__(cls, *args, **kwargs): if not hasattr(Singleton, "_instance"): with Singleton._instance_lock: if not hasattr(Singleton, "_instance"): Singleton._instance = object.__new__(cls) return Singleton._instance obj1 = Singleton() obj2 = Singleton() print(obj1,obj2)
第二种: 通过装饰器
def Sing(cls): _instance = {} def _sig(*args, **kwargs): if cls not in _instance: _instance[cls] = cls(*args, **kwargs) return _instance[cls] return _sig @Sing class A: def __init__(self): self.x = 1 a1 = A() a2 = A() print(a1, a2)
转载博客: https://www.cnblogs.com/huchong/p/8244279.html
邮箱: 1090055252@qq.com