Python 实现常量功能
来自《改善Python程序的91个建议》
常量的风格:
1. 命名全部位大写,用下划线连接各个单词
2. 值一旦绑定便不可再修改
# constant.py import sys class _Const: class ConstError(TypeError): pass class ConstCaseError(ConstError): pass def __setattr__(self, key, value): if key in self.__dict__: raise self.ConstError("Can't change const.%s" % key) if not key.isupper(): raise self.ConstCaseError("const name %s is not all uppercase" % key) self.__dict__[key] = value sys.modules[__name__] = _Const()
使用时直接 import constant ,constant.MY_TEST 即可定义一个常量。
学到的知识点:
sys.modules[__name__] = _Const()
以前都是创建一个实例,为了符合规范,实例的名字要大写,在别处导实例的时候就很丑 😂