const
有什么好处? 最直接的好处是,防止被二次修改导致整个程序崩掉!
第一种方法, 使用enum
来定义变量,防止串改.
from enum import Enum, unique
# 若要不能定义相同的成员值,可以通过 unique 装饰
@unique
class Const(Enum):
a = 0
b = 5
c = 10
Const.a.value
Const.b.value
第二种方法,自己实现一个常量类(利用单例实现)
# coding:utf-8
# Filename:test.py
import sys
class _const:
# 实现单例
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
orig = super(_const, cls)
cls._instance = orig.__new__(cls, *args, **kw)
return cls._instance
class ConstError(TypeError):
def __init__(self, name):
self.msg = "Can't rebind or unbind const instance attribute {0}".format(name)
def __str__(self):
return 'error msg: {}'.format(self.msg)
def __repr__(self):
return self.__str__()
class ConstCaseError(ConstError):
def __init__(self, name):
self.msg = "const name {0} is not all uppercase".format(name)
def __str__(self):
return 'error msg: {}'.format(self.msg)
def __repr__(self):
return self.__str__()
def __setattr__(self, name, value):
if name in self.__dict__:
raise self.ConstError(name)
if not name.isupper():
raise self.ConstCaseError(name)
self.__dict__[name] = value
def __delattr__(self, name):
if name in self.__dict__:
raise self.ConstError(name)
raise self.ConstError(name)
sys.modules[__name__] = _const() # 把Const类注册到sys.modules这个全局字典中(将系统加载的模块列表中的 test 替换为 _const() 实例)
在其他文件中定义常量:
import test
test.AA = 123 # 成功
test.bb = 111 # 报错,常量名需大写
test.AA = 111 # 报错,常量不能修改
del test.AA # 报错,常量不能删除
标签:__,const,常量,python,self,实现,test,def,name
From: https://www.cnblogs.com/amgulen/p/16638416.html