Skip to content

Instantly share code, notes, and snippets.

@ejdecena
Created May 24, 2020 21:57
Show Gist options
  • Save ejdecena/c06720e8a617447de4ad3b2b4d2c5fec to your computer and use it in GitHub Desktop.
Save ejdecena/c06720e8a617447de4ad3b2b4d2c5fec to your computer and use it in GitHub Desktop.
Singleton decorator class.
#!/usr/bin/env python3
"""Singleton decorator class."""
class Singleton:
def __init__(self, cls):
self.__cls = cls
self.__obj = None
def __call__(self, *args, **kwargs):
if not self.__obj:
self.__obj = self.__cls(*args, **kwargs)
return self.__obj
if __name__ == "__main__":
# Testing ...
@Singleton
class Test:
def __init__(self, text):
self.text = text
a = Test("Hello")
b = Test("World")
print("id(a):", id(a), "id(b):", id(b), "Diff:", id(a)-id(b))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment