python怎么定义常量_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(): # 所有的字母需要⼤写
python怎么读的
raise self.ConstCaseError("const name {0} is not all uppercase".format(name))
self.__dict__[name] = value
# 将系统加载的模块列表中的 constant 替换为 _const() 实例
test.py引⽤constan定义常量
import constant
constant.VALUE = 5
constant.VALUE = 4 # ConstError
constant.vaLue = 1 # ConstCaseError

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。