Skip to content

Instantly share code, notes, and snippets.

@ptigas
Created March 6, 2012 19:47
Show Gist options
  • Save ptigas/1988605 to your computer and use it in GitHub Desktop.
Save ptigas/1988605 to your computer and use it in GitHub Desktop.
example of singleton design pattern in python
counter = 1
class TestSingleton:
__instance = None
__var = 0
def __init__(self):
global counter
self.__var = counter
counter += 1
def get_var(self):
return self.__var
@staticmethod
def get_instance():
if TestSingleton.__instance == None :
TestSingleton.__instance = TestSingleton()
return TestSingleton.__instance
t1 = TestSingleton.get_instance()
print id(t1), t1.get_var()
t2 = TestSingleton.get_instance()
print id(t2), t2.get_var()
t3 = TestSingleton.get_instance()
print id(t3), t3.get_var()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment