自定义常量类

116 阅读1分钟
Python定义常量类,两种方式:

1. 通过命名风格来提醒使用者该变量表示常量,如常量名为大写字母,单词用下划线连接,这是约定俗称的方式,其实值是可以改的
2. 通过自定义类来实现常量功能,要求必须字母全为大写,且不可在修改这两个条件

创建一个const.py文件,代码如下:
[Python]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
class _const(object):
class ConstError(TypeError):
pass
class ConstCaseError(ConstError):
pass
def __setattr__(self, key, value):
if self.__dict__.get(key):
raise self.ConstError("Can't change const.%s" % key)
print(key)
if not key.isupper():
raise self.ConstCaseError("const key %s is not all uppercase" % key)
self.__dict__[key] = value
import sys
sys.modules[__name__] = _const()


使用方法,创建一个test.py文件
[Python]
纯文本查看
复制代码
1
2
3
4
5
import const
const.NAME = 'python'
const.AGE = 20
const.AGE = 30


该代码运行会报如下异常:
raise self.ConstError("Can't change const.%s" % key)
const.ConstError: Can't change const.AGE
说明只要定义好一次,后面就不许在修改,常量类没有问题。

更多技术资讯可关注:gzitcast