# 单例模式
class SingleTon:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
_instance = super().__new__(cls, *args, **kwargs)
cls._instance = _instance
return cls._instance
或者
class SingleTon(object):
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(SingleTon, "_instance"): # 反射
SingleTon._instance = object.__new__(cls)
return SingleTon._instance
obj1 = SingleTon()
obj2 = SingleTon()
print(obj1 == obj2)
# 单例模式
class SingleTon:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
_instance = super().__new__(cls, *args, **kwargs)
cls._instance = _instance
return cls._instance
# 验证单列模式
class MyClass(SingleTon):
pass
c1 = MyClass()
c2 = MyClass()
print(id(c1))
print(id(c2))
print(c1 is c2)