Skip to content

Instantly share code, notes, and snippets.

@gamesbook
Created Mar 7, 2021
Embed
What would you like to do?
Example of singleton class
"""
Is this a good idea?
https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
"""
class Singleton:
__instance = None
@staticmethod
def getinstance():
"""Static access method."""
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
def __init__(self):
"""Virtually private constructor."""
if Singleton.__instance is not None:
raise Exception("This class is a singleton!")
else:
Singleton.__instance = self
s = Singleton()
print(s)
t = Singleton()
print(t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment