example18.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """
  2. 元 - meta
  3. 元数据 - 描述数据的数据 - metadata
  4. 元类 - 描述类的类 - metaclass - 继承自type
  5. """
  6. import threading
  7. class SingletonMeta(type):
  8. """自定义元类"""
  9. def __init__(cls, *args, **kwargs):
  10. cls.__instance = None
  11. cls.lock = threading.Lock()
  12. super().__init__(*args, **kwargs)
  13. def __call__(cls, *args, **kwargs):
  14. if cls.__instance is None:
  15. with cls.lock:
  16. if cls.__instance is None:
  17. cls.__instance = super().__call__(*args, **kwargs)
  18. return cls.__instance
  19. class President(metaclass=SingletonMeta):
  20. """总统(单例类)"""
  21. def __init__(self, name, country):
  22. self.name = name
  23. self.country = country
  24. def __str__(self):
  25. return f'{self.country}: {self.name}'
  26. def main():
  27. """主函数"""
  28. p1 = President('特朗普', '美国')
  29. p2 = President('奥巴马', '美国')
  30. p3 = President.__call__('克林顿', '美国')
  31. print(p1 == p2)
  32. print(p1 == p3)
  33. print(p1, p2, p3, sep='\n')
  34. if __name__ == '__main__':
  35. main()