Python常量工具类
1.定义常量类constant.py
# -*- coding: utf-8 -* """常量工具类 author: Jill usage: from constant import _Const const = _Const() const.PI = 3.14 """ class _Const: class ConstError(TypeError): pass class ConstCaseError(ConstError): pass def __setattr__(self, name, value): if name in self.__dict__: raise self.ConstError("Can't change const(%s) value" % name) if not name.isupper(): raise self.ConstCaseError("Const name %s is not all uppercase" % name) self.__dict__[name] = value def __getitem__(self, key): if key in self.__dict__: return self.__dict__[key] else: raise self.ConstError("Can't return const %s, No Existing Key!" % key) def __delattr__(self, name): if name in self.__dict__: raise self.ConstError("Can't unbind const(%s)" % name) raise NameError(name)
2.将常量放在一个模块中common_constant.py
# -*- coding: utf-8 -* """常用常量定义 author: Jill usage: from common_constant import const print(const.ROOT_PATH) """ from common.constant import _Const const = _Const() const.PI = 3.14 if __name__ == "__main__": print(const.PI) print(const['PI'])
3.在其他模块里使用test.py
from common_constant import const print(const.ROOT_PATH)
本博客文章皆出于学习目的,个人总结或摘抄整理自网络。引用参考部分在文章中都有原文链接,如疏忽未给出请联系本人。另外,作为一名菜鸟程序媛,如文章内容有错误,欢迎点击博客右上方的扣扣链接指导交流。