zhangliang91

阅读目录

一、Python定义常量

Python定义常量

constant.py 定义常量类

import sys

class _const:
    # 自定义异常处理
    class ConstError(PermissionError):
        pass
    class ConstCaseError(ConstError):
        pass
    # 重写 __setattr__() 方法
    def __setattr__(self, name, value):
        if name in self.__dict__:  # 已包含该常量,不能二次赋值
            raise self.ConstError("Can\'t change const {0}".format(name))
        if not name.isupper():  # 所有的字母需要大写
            raise self.ConstCaseError("const name {0} is not all uppercase".format(name))
        self.__dict__[name] = value

# 将系统加载的模块列表中的 constant 替换为 _const() 实例
sys.modules[__name__] = _const()

test.py引用constan定义常量

import constant
constant.VALUE = 5
constant.VALUE = 4  # ConstError
constant.vaLue = 1  # ConstCaseError

分类:

技术点:

相关文章:

  • 2021-10-16
  • 2021-10-16
  • 2018-10-26
  • 2021-11-05
  • 2021-11-25
  • 2022-01-02
  • 2021-12-15
  • 2021-09-19
猜你喜欢
  • 2021-12-24
  • 2021-11-05
  • 2021-12-24
  • 2021-10-16
  • 2021-10-25
  • 2021-12-24
  • 2021-12-24
相关资源
相似解决方案