0
点赞
收藏
分享

微信扫一扫

Python实现单例模式常量类

斗米 2022-02-20 阅读 65
import os


class Singleton:
    """
    单例模式
    """
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance


class Const(Singleton):
    """
    单例常量类
    """
    class ConstError(TypeError):
        pass

    class ConstCaseError(ConstError):
        pass

    def __setattr__(self, name, value):
        if name in self.__dict__:
            raise self.ConstError(f"can't change const {name}")
        self.__dict__[name] = value


const = Const()  # 常量实例
举报

相关推荐

0 条评论