1 class Singleton:
2 """ A python singleton """
3
4 class __impl:
5 """ Implementation of the singleton interface """
6
7 def spam(self):
8 """ Test method, return singleton id """
9 return id(self)
10
11
12 __instance = None
13
14 def __init__(self):
15 """ Create singleton instance """
16
17 if Singleton.__instance is None:
18
19 Singleton.__instance = Singleton.__impl()
20
21
22 self.__dict__['_Singleton__instance'] = Singleton.__instance
23
24 def __getattr__(self, attr):
25 """ Delegate access to implementation """
26 return getattr(self.__instance, attr)
27
28 def __setattr__(self, attr, value):
29 """ Delegate access to implementation """
30 return setattr(self.__instance, attr, value)
31
32
33
34 s1 = Singleton()
35 print id(s1), s1.spam()
36
37 s2 = Singleton()
38 print id(s2), s2.spam()
39
40
41
42