python版本的单例模式

# -*- coding:UTF-8 -*- class Singleton(object): __instance = None # 堵死以直接实例化方式创建对象 def __init__(self): raise ValueError('must get instance from method') @classmethod def get_instance(cls): if cls.__instance is None: cls.__instance = super().__new__(cls) return cls.__instance if __name__ == "__main__": s1 = Singleton.get_instance() s2 = Singleton.get_instance() if id(s1) == id(s2): print("s1与s2是相同的对象")

浙公网安备 33010602011771号