Skip to content

Instantly share code, notes, and snippets.

@gamesbook
Created March 7, 2021 06:20
Show Gist options
  • Save gamesbook/31e6109dd278e53f937a9347a8e2f62e to your computer and use it in GitHub Desktop.
Save gamesbook/31e6109dd278e53f937a9347a8e2f62e to your computer and use it in GitHub Desktop.
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