Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

python singleton and singleton borg (See related posts)

Singleton with same states
   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  




You need to create an account or log in to post comments to this site.


Click here to browse all 5350 code snippets

Related Posts