打日志 :单例, _init_flag
背景 非单例
class A: pass a1=A() a2=A() print(id(a1)) print(id(a2)) ''' 1618986824272 1618986826096
a1和a2的id不一样 '''
单例
class Single: _self = None def __new__(cls, *args, **kwargs): if cls._self is None: cls._self=super().__new__(cls) return cls._self def __init__(self): print(".....") s1=Single() s2=Single() print(id(s1)) print(id(s2)) ''' ..... 2252706872672 2252706872672
两个示例的id是一样的 '''
单例 且init 限定仅一次
class A: pass a1=A() a2=A() print(id(a1)) print(id(a2)) ''' 1618986824272 1618986826096 ''' class Single: _self = None # 定义初始化的次数为1次;没定义前 实例化几次,init几次 _init_flag=True def __new__(cls, *args, **kwargs): if cls._self is None: cls._self=super().__new__(cls) return cls._self def __init__(self): if self._init_flag:# 如果是真,说明没被init过,就init print(".....") self._init_flag=False # 打印后就设置为假 s1=Single() s2=Single() print(id(s1)) print(id(s2)) ''' ..... ..... 2252706872672 2252706872672 '''