Created
March 22, 2020 12:30
-
-
Save Ananto30/70750cd6d48a9fd306287db9c456061c to your computer and use it in GitHub Desktop.
Singleton implementation 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 SingletonMeta(type): | |
_instance = None | |
def __call__(self): | |
if self._instance is None: | |
self._instance = super().__call__() | |
return self._instance | |
class Singleton(metaclass=SingletonMeta): | |
# Now implement you singleton class | |
def some_business_logic(self): | |
pass | |
if __name__ == "__main__": | |
s1 = Singleton() | |
s2 = Singleton() | |
# You can check they are both same instance | |
assert(id(s1) == id(s2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment