Created
March 7, 2021 06:20
-
-
Save gamesbook/31e6109dd278e53f937a9347a8e2f62e to your computer and use it in GitHub Desktop.
Example of singleton class
This file contains 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
""" | |
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