1 2 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 3 class Borg: 4 __shared_state = {} 5 def __init__(self): 6 self.__dict__ = self.__shared_state 7 8 a=Borg() 9 a.toto = 12 10 11 b=Borg() 12 print b.toto 13 print id(a),id(b) # different ! but states are sames 14
real Singleton instance
1 2 class Singleton(object): 3 def __new__(type): 4 if not '_the_instance' in type.__dict__: 5 type._the_instance = object.__new__(type) 6 return type._the_instance 7 8 a=Singleton() 9 a.toto = 12 10 11 b=Singleton() 12 print b.toto 13 print id(a),id(b) # the same !! 14