简述
实现了类在当前进程中只有一个实例,比如python-GC
重写__new__
实现单例
class A:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
pass
if __name__ == '__main__':
a = A()
b = A()
print(id(a))
print(id(b))
装饰器实现
def singleTon(cls, *args, **kw):
instances = {}
def inner():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return inner
@singleTon
class A:
pass
标签:__,args,instance,常见,instances,单例,设计模式,cls
From: https://www.cnblogs.com/aleiyoy/p/16628170.html