python 装饰器实现单例

来源:互联网 发布:万方数据库和中国知网 编辑:程序博客网 时间:2024/06/04 00:38
  1. def Singleton(cls):  
  2.     _instance = {}  
  3.     def _singleton(*args, **kargs):  
  4.         if cls not in _instance:  
  5.             _instance[cls] = cls(*args, **kargs)  
  6.         return _instance[cls]  
  7.     return _singleton  
  8.  
  9.  
  10. @Singleton  
  11. class A(object):  
  12.     a = 1  
  13.     def __init__(self, x = 0):  
  14.         self.x = x  
  15.   
  16.   
  17. a1 = A(2)  
  18. a2 = A(3)  
  19. print id(a1)  
  20. print id(a2)  
  21. print a1.x  
  22. print a2.x  
  23.   
  24.   
  25. ''''' 
  26. ---------------------------------------- 
  27. 45838576 
  28. 45838576 
  29. 2 
  30. 2 
原创粉丝点击