Created
May 14, 2025 14:04
-
-
Save keuv-grvl/b97e6c6865bd6f8dbaa5fb7335295dc3 to your computer and use it in GitHub Desktop.
Singleton pattern
This file contains hidden or 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): | |
_instances = {} | |
def __call__(cls, *args, **kwargs): | |
if cls not in cls._instances: | |
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) | |
return cls._instances[cls] | |
class MyClass(metaclass=Singleton): | |
def __init__(self): | |
self.a = 234 | |
aa = MyClass() | |
aa.val # 234 | |
bb = MyClass() | |
bb.val = 654 | |
aa.val # 654 | |
id(aa) == id(bb) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment