example10.py 938 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """
  2. 装饰类的装饰器 - 单例模式 - 一个类只能创建出唯一的对象
  3. 上下文语法:
  4. __enter__ / __exit__
  5. """
  6. import threading
  7. from functools import wraps
  8. def singleton(cls):
  9. """单例装饰器"""
  10. instances = {}
  11. lock = threading.Lock()
  12. @wraps(cls)
  13. def wrapper(*args, **kwargs):
  14. if cls not in instances:
  15. with lock:
  16. if cls not in instances:
  17. instances[cls] = cls(*args, **kwargs)
  18. return instances[cls]
  19. return wrapper
  20. @singleton
  21. class President():
  22. def __init__(self, name, country):
  23. self.name = name
  24. self.country = country
  25. def __str__(self):
  26. return f'{self.country}: {self.name}'
  27. def main():
  28. print(President.__name__)
  29. p1 = President('特朗普', '美国')
  30. p2 = President('奥巴马', '美国')
  31. print(p1 == p2)
  32. print(p1)
  33. print(p2)
  34. if __name__ == '__main__':
  35. main()