python本身没有提供常量的的功能,需要自己编写并在python的安装目录下的Lib目录中导入。
1 编写常量功能:
# Filename: const.py
# 定义一个常量类实现常量的功能
#
# 该类定义了一个方法__setattr()__,和一个异常ConstError, ConstError类继承
# 自类TypeError. 通过调用类自带的字典__dict__, 判断定义的常量是否包含在字典
# 中。如果字典中包含此变量,将抛出异常,否则,给新创建的常量赋值。
# 最后两行代码的作用是把const类注册到sys.modules这个全局字典中。
class _const:
class ConstError(TypeError):pass
def __setattr__(self, name, value): # 定义方法__setattr()__
if self.__dict__.has_key(name): # 从字典中查找
raise self.ConstError, "Can't rebind const (%s)" %name
self.__dict__[name]=value
import sys
sys.modules[__name__] = _const()
2 保存后命名为const.py并保存在python的安装目录下的Lib目录
3 使用:
import const #引入该模块
const.value= 5
print const.value
按F5执行后输出 5
import const <span style="font-family: Arial, Helvetica, sans-serif;">#引入该模块</span>
const.value= 5
print const.value
const.value= 6 #执行后此处会报错