Last active
September 28, 2020 20:10
-
-
Save BuildWithLal/3938daf1470a3b7ed7d167976a329638 to your computer and use it in GitHub Desktop.
Create a singleton class using Python 3
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(object): | |
def __new__(cls): | |
if not hasattr(cls, 'instance') or not cls.instance: | |
cls.instance = super().__new__(cls) | |
return cls.instance | |
obj1 = Singleton() | |
obj2 = Singleton() | |
print(obj1 is obj2) # True | |
print(obj1 == obj2) # True | |
print(type(obj1) == type(obj2)) # True | |
print(id(obj1) == id(obj2)) # True | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool 👍
Thank you