一、基于__new__
class Single: _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Single, cls).__new__(cls, *args, **kwargs) return cls._instance class Demon(Single): def foo(self): print("Hi") d1 = Demon() d2 = Demon() print(id(d1)) # 2110545800776 print(id(d2)) # 2110545800776
二、基于模块
重点:
1、一个模块在一个项目中只加载一次, 然后从pyc中取
2、一个对象只加载一次
注意:单例对象执行同一个内存空间