britodfbr

singleton#2

Jan 17th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.50 KB | None | 0 0
  1. class Singleton(type):
  2.     def __init__(self, name, bases, dict):
  3.         super(Singleton, self).__init__(name, bases, dict)
  4.         self.instance = None
  5.  
  6.     def __call__(self, *args, **kw):
  7.         if self.instance is None:
  8.             self.instance = super(Singleton, self).__call__(*args, **kw)
  9.         return self.instance
  10.  
  11.  
  12. class MyClass(object, metaclass=Singleton):
  13.     pass
  14.  
  15.  
  16. if __name__ == '__main__':
  17.     a = MyClass()
  18.     b = MyClass()
  19.  
  20.     print(id(a), id(b))
  21.     print(a is b)
Advertisement
Add Comment
Please, Sign In to add comment