閱讀目錄
一、Python定義常量
Python定義常量
constant.py 定義常量類
import sys
class _const:
# 自定義異常處理
class ConstError(PermissionError):
pass
class ConstCaseError(ConstError):
pass
# 重寫 __setattr__() 方法
def __setattr__(self, name, value):
if name in self.__dict__: # 已包含該常量,不能二次賦值
raise self.ConstError("Can't change const {0}".format(name))
if not name.isupper(): # 所有的字母需要大寫
raise self.ConstCaseError("const name {0} is not all uppercase".format(name))
self.__dict__[name] = value
# 將系統加載的模塊列表中的 constant 替換為 _const() 實例
sys.modules[__name__] = _const()
test.py引用constan定義常量
import constant
constant.VALUE = 5
constant.VALUE = 4 # ConstError
constant.vaLue = 1 # ConstCaseError