python: 单例装饰器
3 月,跳不动了?>>> singleton 的三种写法 # # instance_map = {} # # # def get_instance(cls, *args, **kwargs): # if cls not in instance_map: # instance_map[cls] = cls(*args, **kwargs) # # log # instance = instance_map[cls] # print(f'id:{id(instance)}') # return instance # # # def singleton(cls): # def on_call(*args, **kwargs): # return get_instance(cls, *args, **kwargs) # return on_call def singleton(cls): instance = None def wrapper(*args, **kwargs): nonlocal instance if instance: return instance instance = cls(*args, **kwargs) print(f"id:{id(instance)}") return instance return wrapper class Singleton