#pragma section-numbers off = Singleton = See also http://c2.com/cgi/wiki?PythonSingleton and http://www.python.org/workshops/1997-10/proceedings/savikko.html === classmethod === ---- ''' pro ''' * You can use both as simple class or as a singleton. * You do not need to write code for each class you want to act as singleton. ---- ''' cons ''' {{{ #!python # Code is Public Domain. class Singleton: _singleton = None def getSingleton(cls): if not isinstance(cls._singleton,cls): cls._singleton = cls() return cls._singleton getSingleton = classmethod(getSingleton) if __name__=='__main__': class Test(Singleton): def test(self): print self.__class__,id(self) class Test1(Test): def test1(self): print self.__class__,id(self),'Test1' t1 = Test.getSingleton() t2 = Test.getSingleton() t1.test() t2.test() assert(isinstance(t1,Test)) assert(isinstance(t2,Test)) assert(id(t1)==id(t2)) t1 = Test1.getSingleton() t2 = Test1.getSingleton() assert(isinstance(t1,Test1)) assert(isinstance(t2,Test1)) assert(id(t1)==id(t2)) t1.test() t1.test1() t2.test() t1.test1() t3 = Test.getSingleton() t3.test() assert(isinstance(t3,Test)) }}}