def singleton(cls):
__instance = {}
def inner(class_id: int | str = None):
if class_id is None:
key = str(cls)
else:
key = str(cls) + str(class_id)
if key not in __instance:
__instance[key] = cls()
return __instance[key]
return inner
使用:
@singleton
class A:
def __init__(self):
pass
a1 = A()
a2 = A(1)
print(id(a1) == id(a2))
# 输出False
a3 = A()
print(id(a1) == id(a3))
# 输出True