class Singleton:
# 私有化实例,单例的地址就存在于__instance
__instance = None
# 因为python实例化对象、向内存要地址时实际调用的是__new__,因此重写__new__
def __new__(cls):
if cls.__instance is None:
cls.__instance = object.__new__(cls) # 需要借助object的__new__创建对象
return cls.__instance
else:
return cls.__instance
s = Singleton()
s1 = Singleton()
print(s)
print(s1)
s与s1的地址一致。