构建常量
Python中不存在像const那样的常量关键字,只是在内建空间中提供了一小部分常量,比如True、False、None等。那么在Python中如何使用常量呢?一般来说有如下两种方法:
- 通过命名风格来提示使用者该变量代表的意义为常量,比如MAX_NUMBER、TOTAL。然而这种方式并没有真正实现常量,其对应的值仍然可以被改变,这只是一种约定俗成的风格。
- 通过自定义类实现常量功能。这要求符合“命名全部为大写”和“值一旦被绑定便不可再修改”这两个条件。下面我们就来看一个例子。
#coding:utf-8 class _const: class ConstError(TypeError): pass class ConstCaseError(ConstError): pass def __setattr__(self, name, value): if name in self.__dict__: raise self.ConstError("can't change const %s" % name) if not name.isupper(): raise self.ConstCaseError('const name "%s" is not all uppercase' % name) self.__dict__[name] = value import sys sys.modules[__name__] = _const()
- 如果上面的代码对应的模块名为const,使用的时候只要import const,便可以直接定义常量了,比如:
import const const.AUTHOR = 'test'
- 上面的const.AUTHOR定义后便不可再更改,因此const.AUTHOR = 'anonymity’会抛出const.ConstError异常,而常量名称如果小写,如const.author = ‘test’,也会抛出const.ConstCaseError异常。
# 将常量集中到一个文件 > 无论采用那种方式实现常量,都建议将常量集中到一个文件中,因为这样有利于维护,一旦修改常量的值,可以集中统一进行而不是逐个进行检查。
- 举个例子
#coding:utf-8
class _const:
class ConstError(TypeError): pass
class ConstCaseError(ConstError): pass
def __setattr__(self, name, value):
if name in self.__dict__:
raise self.ConstError("can't change const %s" % name)
if not name.isupper():
raise self.ConstCaseError('const name "%s" is not all uppercase' % name)
self.__dict__[name] = value
const = _const()
const.PI = 3.14
- 假设上面的模组名是cosnt,使用文件可以写成:
from const import const
print(const.PI)
版权声明:本文为my_precious原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。