Python 官方文档:入门教程 => 点击学习
python中不存在像const那样的常量关键字,只是在内建空间中提供了一小部分常量,比如True、False、None等。那么在Python中如何使用常量呢?一般来说有如下两种方法: 通过命名风格来提示使用者该变量代表的
python中不存在像const那样的常量关键字,只是在内建空间中提供了一小部分常量,比如True、False、None等。那么在Python中如何使用常量呢?一般来说有如下两种方法:
通过自定义类实现常量功能。这要求符合“命名全部为大写”和“值一旦被绑定便不可再修改”这两个条件。下面我们就来看一个例子。
#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 = 'tzw0745'
上面的const.AUTHOR定义后便不可再更改,因此const.AUTHOR = ‘anonymity’会抛出const.ConstError异常,而常量名称如果小写,如const.author = ‘tzw0745’,也会抛出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)
--结束END--
本文标题: 构造Python中的常量类
本文链接: https://www.lsjlt.com/news/188948.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0