Skip to content

Instantly share code, notes, and snippets.

@lalatgithub
Last active September 28, 2020 20:10
Show Gist options
  • Save lalatgithub/3938daf1470a3b7ed7d167976a329638 to your computer and use it in GitHub Desktop.
Save lalatgithub/3938daf1470a3b7ed7d167976a329638 to your computer and use it in GitHub Desktop.
Create a singleton class using Python 3
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
@EstebanJoaquinIgnacio
Copy link

Cool 👍
Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment