单例设计模式

  1. class MusicPlayer(object):
  2. __instance = None
  3. __is_first = True
  4. def __new__(cls, *args, **kwargs):
  5. if cls.__instance is None:
  6. cls.__instance = super().__new__(cls)
  7. return cls.__instance
  8. def __init__(self, name):
  9. if self.__is_first:
  10. self.name = name
  11. self.__is_first = False
  12. a = MusicPlayer("a")
  13. b = MusicPlayer("b") # 第二次不会赋值
  14. print(a is b) # True