Python 3 Singleton
The snippet can be accessed without any authentication.
Authored by
Mikaël Guichard
Edited
Singleton.py 590 B
def singleton(cls):
instance = None
def ctor(*args, **kwargs):
nonlocal instance
if not instance:
instance = cls(*args, **kwargs)
return instance
return ctor
@singleton
class Bar:
def __init__(self, val):
self.val = val
# ----------------------------------------------------
a = Bar("var1") # Le paramètre var1 est enregistré lors de la création de l'instance
b = Bar("var2") # Récupération de l'instance déjà créée. Le paramètre ne sera donc pas enregistré
print(a.val, id(a))
print(b.val, id(b))
print(a is b)
Please register or sign in to comment