from functools import wraps
def single(cls):
sets={}
print(sets)
@wraps(cls)
def wrapper(*args,**kw):
if "ex" not in sets:
sets["ex"]=cls(*args,**kw)
return sets["ex"]
return wrapper
@single
class B:
pass
b=B()
b.a="hello bachelor"
a=B()
d=single(B)
print(c.a)
Singleton pattern implemented through decorators, but there is one area that is not particularly understood:
Create two instances of B through object=B () in thecode, why
sets={}
print(sets)
this paragraph was executed only once.
another puzzle is
@decorator
class B:
pass
decorator(B)
but if d=single (B) is used in the code, the sets= {} section will be executed.