Revision 5 as of 2003-11-17 22:11:21

Clear message

Singleton

See also http://c2.com/cgi/wiki?PythonSingleton and http://www.python.org/workshops/1997-10/proceedings/savikko.html

classmethod


pro


cons

   1 # Code is Public Domain.
   2 class Singleton:
   3     _singleton = None
   4     
   5     def getSingleton(cls):
   6         if not Singleton._singleton:
   7             Singleton._singleton = cls()
   8         return Singleton._singleton
   9 
  10     getSingleton = classmethod(getSingleton)
  11 
  12 
  13 class Test(Singleton):
  14     def test(self):
  15         print self.__class__,id(self)
  16 
  17 
  18 t1 = Test.getSingleton()
  19 t2 = Test.getSingleton()
  20 
  21 t1.test()
  22 t2.test()

Unable to edit the page? See the FrontPage for instructions.