目录
1.问题
如何在python中使用自定义常量
2.说明
使用类拦截属性设置来自定义常量
python3 中默认自动继承新式类object
3.实现代码
class _const:
class ConstError(Exception):pass
class UpperCaseError(ConstError):pass
def __setattr__(self,name,value):#拦截属性设置
if name in self.__dict__.keys():#判断属性是否存在
raise self.ConstError("can't bind const")
if not name.isupper():
raise self.UpperCaseError("the '%s' is not all uppercase"%name)
self.__dict__[name]=value
import sys
sys.moduels[__name__]=_const()#将类生成的实例绑定到模块名const 直接使用const来操作常量
#文件名const.py
测试代码tConst.py
import const
const.V=7
const.test=10
#此处报绑定大小写错误
print(const.V)
const.V=5
#此处会报错
print(const.V)