Last active
December 15, 2019 14:02
-
-
Save tweakimp/31874dc59334b6967abfcce237942298 to your computer and use it in GitHub Desktop.
Singleton
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): | |
""" | |
Metaclass. | |
Only allows the creation of one instance, all other tries return | |
the same instance of the first creation. | |
Use: | |
class Test(metaclass=Singleton): | |
... | |
""" | |
def __init__(self, *args, **kwargs): | |
self.__instance = None | |
super().__init__(*args, **kwargs) | |
def __call__(self, *args, **kwargs): | |
if self.__instance is None: | |
self.__instance = super().__call__(*args, **kwargs) | |
return self.__instance | |
if __name__ == "__main__": | |
class Test(metaclass=Singleton): | |
def __init__(self): | |
print("Initializing Test") | |
a = Test() | |
b = Test() | |
c = Test() | |
print(a is b) | |
print(b is c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment