类构造单例模式
class Singleton:
'''通过类构造单例'''
obj = None
def __new__(cls):
if cls.obj is None:
cls.obj = object.__new__(cls)
return cls.obj
def __init__(self):
self.x = 123
self.y = 321
a = Singleton()
b = Singleton()
c = Singleton()
print(a is b is c)
通过装饰器构造单例
def singleton_deco(cls):
'''单例装饰器'''
obj = None
def wrapper(*args, **kwargs):
nonlocal obj
if obj is None:
obj = cls(*args, **kwargs)
return obj
return wrapper
@singleton_deco
class Other:
pass
x = Other()
y = Other()
print(x is y)