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
1 # Code is Public Domain.
2 class Singleton:
3 _singleton = None
4 def getSingleton(cls):
5 if not isinstance(cls._singleton,cls):
6 cls._singleton = cls()
7 return cls._singleton
8
9 getSingleton = classmethod(getSingleton)
10
11 if __name__=='__main__':
12 class Test(Singleton):
13 def test(self):
14 print self.__class__,id(self)
15
16 class Test1(Test):
17 def test1(self):
18 print self.__class__,id(self),'Test1'
19 