❥单例模式❥

# 单例模式
class Index:
    # 方法1
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = object.__new__(cls, *args , **kwargs)
        return cls._instance

    # 方法2
    def __new__(cls *args, **kwargs):
        if not hasattr(cls, '_instance'):
            setattr(cls, '_instance', super().__new__(cls, *args, **kwargs))
        return getattr(cls, '_instance')

    # 方法3 
    @classmethod
    def index(cls):
        if not cls._instance:
            cls._instance = cls()
        return cls._instance

123

posted @ 2019-11-15 09:53  LD_Dragon  阅读(152)  评论(0编辑  收藏  举报