1、元类实现
1 class Singleton(type): 2 def __init__(self, *args, **kwargs): 3 super().__init__(*args, **kwargs) 4 self._instance = None 5 6 # 重写__call__ 7 def __call__(self, *args, **kwargs): 8 if not self._instance: 9 self._instance = super().__call__(*args, **kwargs) 10 return self._instance 11 12 13 class Valley(metaclass=Singleton): 14 ... 15 16 17 a = Valley() 18 b = Valley() 19 print(id(a), id(b))
2、装饰器实现
1 def singleton(cls): 2 _instance = {} 3 4 def wrapper(*args, **kwargs): 5 if cls not in _instance: 6 _instance[cls] = cls(*args, **kwargs) 7 return _instance[cls] 8 9 return wrapper 10 11 12 @singleton 13 class Valley(): 14 ... 15 16 17 a = Valley() 18 b = Valley() 19 print(id(a), id(b))
标签:__,Valley,创建,self,args,instance,单例,kwargs,设计模式 From: https://www.cnblogs.com/shixiaogu/p/16716577.html