python —— 装饰器实现单例模式

代码:(来自:https://blog.csdn.net/weixin_44689630/article/details/99829998)


instances = {}


def singleton(cls):
    def get_instance(*args, **kwargs):
        cls_name = cls.__name__
        print('===== 1 ====')
        if cls_name not in instances:
            print('===== 2 ====')
            instance = cls(*args, **kwargs)
            instances[cls_name] = instance
        return instances[cls_name]

    return get_instance


@singleton
class User:
    _instance = {}

    def __init__(self, name):
        print('===== 3 ====')
        self.name = name


if __name__ == '__main__':
    u1 = User("np1")
    # == == = 1 == ==
    # == == = 2 == ==
    # == == = 3 == ==
    u1.age = 20
    u2 = User("np2")
    # == == = 1 == ==
    print(u2.age)
    # 20
    print(u1 is u2)
    # True






运行效果:

image





posted on 2025-12-13 15:52  Angry_Panda  阅读(4)  评论(0)    收藏  举报

导航