今天看书《编写高质量代码:改善python程序的91个建议》时阅读到关于常量的管理。觉得很有启发。遂记录在此。
如果有争议和版权问题,请联系我,删除相关内容。
python内置的常量只有None, True, False。没有提供直接定义常量的方法。因此,在python代码中定义常量好的方式就是编写一个类模块,专门存储常量。常量的命名方式应该是大写字母加下划线。具体如下:
class _const:
class ConstError(TypeError): pass
class ConstCaseError(ConstError): pass
def __setattr__(self, name, value):
if self.__dict__.has_key(name):
raise self.ConstError, "Can not change const %s" % name
if not name.isupper():
raise self.ConstCaseError, "const name %s is not all upper" % name
self.__dict__[name] = value
import sys
sys.modules[__name__] = _const()
将上述代码保存为const.py
使用时只需要
import const
const.IP = '127.0.0.1'
保存为constant.py
其他模块使用常量是只需要:
from constant import const
print const.IP