class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance s1 = Singleton() s2 = Singleton() assert id(s1) == id(s2)
利用模块实现单例模式
Borg模式
class Borg: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state