前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >构造Python中的常量类

构造Python中的常量类

作者头像
py3study
发布2020-01-07 11:16:42
3.2K0
发布2020-01-07 11:16:42
举报
文章被收录于专栏:python3python3

构建常量

Python中不存在像const那样的常量关键字,只是在内建空间中提供了一小部分常量,比如True、False、None等。那么在Python中如何使用常量呢?一般来说有如下两种方法:

通过命名风格来提示使用者该变量代表的意义为常量,比如MAX_NUMBER、TOTAL。然而这种方式并没有真正实现常量,其对应的值仍然可以被改变,这只是一种约定俗成的风格。

通过自定义类实现常量功能。这要求符合“命名全部为大写”和“值一旦被绑定便不可再修改”这两个条件。下面我们就来看一个例子。

代码语言:javascript
复制
#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,便可以直接定义常量了,比如:

代码语言:javascript
复制
import const
const.AUTHOR = 'tzw0745'

上面的const.AUTHOR定义后便不可再更改,因此const.AUTHOR = ‘anonymity’会抛出const.ConstError异常,而常量名称如果小写,如const.author = ‘tzw0745’,也会抛出const.ConstCaseError异常。


将常量集中到一个文件

无论采用那种方式实现常量,都建议将常量集中到一个文件中,因为这样有利于维护,一旦修改常量的值,可以集中统一进行而不是逐个进行检查。

举个例子

代码语言:javascript
复制
#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,使用文件可以写成:

代码语言:javascript
复制
from const import const
print(const.PI)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 构建常量
  • 将常量集中到一个文件
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档