Skip to content

Instantly share code, notes, and snippets.

@amitt001
Last active October 22, 2015 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitt001/c032b0b83b0bfe49ccb7 to your computer and use it in GitHub Desktop.
Save amitt001/c032b0b83b0bfe49ccb7 to your computer and use it in GitHub Desktop.
Singleton class in Python
#http://elbenshira.com/blog/singleton-pattern-in-python/
#http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
class Counter:
def __init__(self):
self.count = 0
def inc(self):
self.count += 1
print type(Counter) # <type 'classobj'>
Counter = singleton(Counter)
print type(Counter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment