Posted By

fnl on 08/13/11


Tagged


Versions (?)

Singleton class


 / Published in: Python
 

  1. class Singleton(type):
  2. """Singleton metaclass. Do NOT inherit!
  3.  
  4. Usage:
  5.  
  6. class MyClass(object):
  7. __metaclass__ = Singleton
  8. ...
  9. """
  10.  
  11. def __init__(mcs, name, bases, dic):
  12. super(Singleton, mcs).__init__(name, bases, dic)
  13. mcs.__instance = None
  14.  
  15. def __call__(mcs, *args, **kw):
  16. if mcs.__instance is None:
  17. mcs.__instance = super(Singleton, mcs
  18. ).__call__(*args, **kw)
  19. return mcs.__instance

Report this snippet  

You need to login to post a comment.