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))
3、重写__new__
前面两种方式是之前记录的,通过继承或者装饰器来实现,相对可能要复杂点,最近发现一种方式是可以直接在类的内部实现,重写__new__双下方法
1 class Valley: 2 _instance = None 3 4 def __new__(cls, *args, **kwargs): 5 if cls._instance is None: 6 cls._instance = super().__new__(cls, *args, **kwargs) 7 return cls._instance 8 9 10 if __name__ == '__main__': 11 a = Valley() 12 b = Valley() 13 print(id(a), id(b))
再次创建新的实例时会返回旧的实例