Last active
October 8, 2018 16:39
-
-
Save ZoranPandovski/0ecfdd002321effa005e1a8d4f6a30b9 to your computer and use it in GitHub Desktop.
Singleton dp in Python
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(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