Skip to content

Instantly share code, notes, and snippets.

@ZoranPandovski
Last active October 8, 2018 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZoranPandovski/0ecfdd002321effa005e1a8d4f6a30b9 to your computer and use it in GitHub Desktop.
Save ZoranPandovski/0ecfdd002321effa005e1a8d4f6a30b9 to your computer and use it in GitHub Desktop.
Singleton dp in Python
class Singleton(type):
def __init__(cls, name, bases, attrs, **kwargs):
super().__init__(name, bases, attrs)
cls._instance = None
def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
class SingletonClass(metaclass=Singleton):
pass
if __name__ == "__main__":
obj1 = SingletonClass()
obj2 = SingletonClass()
print(obj1 is obj2)
print(id(obj1))
print(id(obj2))
#OUTPUT
#True
#140189813742112
#140189813742112
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment