Python常量类

class _const:
    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}")
        if not name.isupper():
            raise self.ConstCaseError(f'const name {name} is not all uppercase')
        self.__dict__[name] = value


const = _const()

使用

from constant import const
const.MY_CONSTANT = 1
const.MY_SECOND_CONSTANT = 2
const.MY_THIRD_CONSTANT = 'a'
const.MY_FORTH_CONSTANT = 'b'
posted @ 2019-11-25 17:54  公众号python学习开发  阅读(258)  评论(0编辑  收藏  举报