单例模式 发表于 2019-12-01 | 分类于 python , 设计模式 单例模式 :是指一个类只会有一个实例,主要是用来控制对资源的访问; 在 __new__ 中保证了每次实例化时都返回同一个实例,但是 __init__方法却每次实例化时都执行,因此可以添加一个参数 来指明实例化的执行状态。 1234567891011121314151617181920212223class Singleton: inited = False def __new__(cls, *args, **kwargs): if not hasattr(cls, "_instance"): cls._instance = super().__new__(cls) else: cls.inited = True return cls._instance class Person(Singleton): def __init__(self, name, age=80): if not self.inited: self.name = name self.age = age a = Person("leon", 23) b = Person("tom", 27) print(a.name) # >>> "leon" print(b.name) # >>> "leon"