装饰器
def Singleton(func): _instance = {} def _singleton(*args, **kargs): if func not in _instance: _instance[func] = func(*args, **kargs) return _instance[func] return _singleton @Singleton class A(object): a = 1 def __init__(self, x=0): self.x = x a1 = A(2) a2 = A(3) print(id(a1)) print(id(a2))
基于__new__方法实现
class Singleton:
instance = {}
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "instance"):
cls.instance = super().__new__()
return cls.instance
class Foo(Singleton):
pass
a = Foo()
b = Foo()
c = Foo()
print(id(a))
print(id(b))
print(id(c))