Last active
December 12, 2021 03:10
-
-
Save mdippery/037d6a9a2fb433f6bd2160c6b41cebb4 to your computer and use it in GitHub Desktop.
Creating a Singleton in Python
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
class Singleton(type): | |
def __init__(cls, name, bases, dict): | |
super(Singleton, cls).__init__(name, bases, dict) | |
cls.instance = None | |
def __call__(cls, *args, **kwargs): | |
if cls.instance is None: | |
cls.instance = super(Singleton, cls).__call__(*args, **kwargs) | |
return cls.instance | |
class MySingleton(object): | |
__metaclass__ = Singleton | |
a = MySingleton() | |
b = MySingleton() | |
c = MySingleton() | |
print a is b | |
print b is c | |
print a is c | |
print a == b | |
print b == c | |
print a == c | |
print hash(a) | |
print hash(b) | |
print hash(c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment