码迷,mamicode.com
首页 > 编程语言 > 详细

Python定义常量

时间:2019-10-16 13:47:26      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:change   str   ant   ISE   目录   实例   二次   mat   sys   


阅读目录

一、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

Python定义常量

标签:change   str   ant   ISE   目录   实例   二次   mat   sys   

原文地址:https://www.cnblogs.com/zhangliang91/p/11684638.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!