❥单例模式❥

# 单例模式
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

上一篇:sqlalchemy 源码分析之create_engine引擎的创建


下一篇:drf 请求模块