zoukankan      html  css  js  c++  java
  • Python定义常量


    阅读目录

    一、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
    
  • 相关阅读:
    O(n^2)的排序方法
    99乘法表
    excel 转 csv
    批量关闭 excel
    tomcat 加入服务
    文件打包 zip
    字符串转换
    List数组种删除数据
    mybatis 批量上传
    sql server 查询表字段及类型
  • 原文地址:https://www.cnblogs.com/zhangliang91/p/11684638.html
Copyright © 2011-2022 走看看