# 单例模式 class Singleton(object): __instance = None __isFirstInit = True # 理解__new__是创建对象的 def __new__(cls, *args, **kwargs): # if not cls.__instance: # cls.__instance = super().__new__(cls, *args, **kwargs) # return cls.__instance if cls.__isFirstInit: cls.__instance = super().__new__(cls, *args, **kwargs) cls.__isFirstInit = False return cls.__instance = super().__new__(cls, *args, **kwargs) # 理解__init__是初始化对象,为对象绑定属性的 def __init__(self, *args, **kwargs): self.name = "Will" self.age = 23 def __str__(self): return f"Singleton({self.name},{self.age})" s1 = Singleton() s2 = Singleton() print(s1, s2) # Singleton(Will,23) Singleton(Will,23) print(id(s1), id(s2)) # 1823388319984 1823388319984 s2.name = "Smith" print(s1, s2) # Singleton(Smith,23) Singleton(Smith,23)