Created
May 24, 2020 21:57
-
-
Save ejdecena/c06720e8a617447de4ad3b2b4d2c5fec to your computer and use it in GitHub Desktop.
Singleton decorator class.
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
#!/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