Last active
October 22, 2015 13:03
-
-
Save amitt001/c032b0b83b0bfe49ccb7 to your computer and use it in GitHub Desktop.
Singleton class in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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