Python中的单例模式

# 单例模式:只有一个对象生成的类
class Singleton:
    # 私有化 单例的地址就存在于__instance
    __instance = None

    # 重写__new__
    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = object.__new__(cls)
        return cls.__instance


s1 = Singleton()
s2 = Singleton()
print(s1)
print(s2)
posted @ 2021-02-22 09:43  kevin.l  阅读(48)  评论(0编辑  收藏  举报