Python实现Const详解


Posted in Python onJanuary 27, 2015

python语言本身没有提供const,但实际开发中经常会遇到需要使用const的情形,由于语言本身没有这种支出,因此需要使用一些技巧来实现这一功能

定义const类如下

import sys

class Const(object):

    class ConstError(TypeException): pass

    def __setattr__(self, key, value):

        if self.__dict__.has_key(key):

            raise self.ConstError, "Changing const.%s" % key

        else:

            self.__dict__[key] = value

    def __getattr__(self, key):

        if self.__dict__.has_key(key):

            return self.key

        else:

            return None

sys.modules[__name__] = Const()

使用sys.modules[name]可以获取一个模块对象,并可以通过该对象获取模块的属性,这儿使用了sys.modules向系统字典中注入了一个Const对象从而实现了在执行import const时实际获取了一个Const实例的功能,sys.module在文档中的描述如下

sys.modules
This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object.
sys.modules[name] = Const()这条语句将系统已加载的模块列表中的const替换为了Const(),即一个Const实例

这样,整个工程需要使用的常量都应该定义在一个文件中,如下

from project.utils import const

const.MAIL_PROTO_IMAP = 'imap'

const.MAIL_PROTO_GMAIL = 'gmail'

const.MAIL_PROTO_HOTMAIL = 'hotmail'

const.MAIL_PROTO_EAS = 'eas'

const.MAIL_PROTO_EWS = 'ews'

这儿首先需要说明python中import module和from module import的区别

import module只是将module的name加入到目标文件的局部字典中,不需要对module进行解释
from module import xxx需要将module解释后加载至内存中,再将相应部分加入目标文件的局部字典中
python模块中的代码仅在首次被import时被执行一次
from project.utils import const时,发生了sys.modules[name] = Const(),此时const模块已经加载进入内存,系统字典中也已经有了Const对象,随后既可以使用Const实例了

在其他文件中需要使用常量值时,以如下方式调用

from project.apps.project_consts import const

print const.MAIL_PROTO_IMAP
Python 相关文章推荐
一个基于flask的web应用诞生 bootstrap框架美化(3)
Apr 11 Python
Django 前后台的数据传递的方法
Aug 08 Python
python tensorflow学习之识别单张图片的实现的示例
Feb 09 Python
python PyTorch参数初始化和Finetune
Feb 11 Python
python保存网页图片到本地的方法
Jul 24 Python
5款Python程序员高频使用开发工具推荐
Apr 10 Python
对Python中TKinter模块中的Label组件实例详解
Jun 14 Python
django mysql数据库及图片上传接口详解
Jul 18 Python
python高阶函数map()和reduce()实例解析
Mar 16 Python
mac 上配置Pycharm连接远程服务器并实现使用远程服务器Python解释器的方法
Mar 19 Python
Python实现Appium端口检测与释放的实现
Dec 31 Python
浅谈tf.train.Saver()与tf.train.import_meta_graph的要点
May 26 Python
python映射列表实例分析
Jan 26 #Python
Python操作MySQL简单实现方法
Jan 26 #Python
Python中的is和id用法分析
Jan 26 #Python
Python的批量远程管理和部署工具Fabric用法实例
Jan 23 #Python
推荐11个实用Python库
Jan 23 #Python
17个Python小技巧分享
Jan 23 #Python
Windows8下安装Python的BeautifulSoup
Jan 22 #Python
You might like
destoon各类调用汇总
2014/06/20 PHP
php实现的Captcha验证码类实例
2014/09/22 PHP
ThinkPHP提示错误Fatal error: Allowed memory size的解决方法
2015/02/12 PHP
jQuery基本过滤选择器使用介绍
2013/04/18 Javascript
微信小程序 location API实例详解
2016/10/02 Javascript
js实现刷新页面后回到记录时滚动条的位置【两种方案可选】
2016/12/12 Javascript
浅谈vue中改elementUI默认样式引发的static与assets的区别
2018/02/03 Javascript
vue弹窗组件使用方法
2018/04/28 Javascript
使用vue-infinite-scroll实现无限滚动效果
2018/06/22 Javascript
laydate时间日历插件使用方法详解
2018/11/14 Javascript
Vue 微信端扫描二维码苹果端却只能保存图片问题(解决方法)
2020/01/19 Javascript
PHP webshell检查工具 python实现代码
2009/09/15 Python
进一步探究Python的装饰器的运用
2015/05/05 Python
Python中的localtime()方法使用详解
2015/05/22 Python
谈谈如何手动释放Python的内存
2016/12/17 Python
Python科学计算之NumPy入门教程
2017/01/15 Python
快速实现基于Python的微信聊天机器人示例代码
2017/03/03 Python
django静态文件加载的方法
2018/05/20 Python
mvc框架打造笔记之wsgi协议的优缺点以及接口实现
2018/08/01 Python
Python实现从SQL型数据库读写dataframe型数据的方法【基于pandas】
2019/03/18 Python
PyQt5基本控件使用之消息弹出、用户输入、文件对话框的使用方法
2019/08/06 Python
Python netmiko模块的使用
2020/02/14 Python
Python多线程获取返回值代码实例
2020/02/17 Python
python的列表List求均值和中位数实例
2020/03/03 Python
python ETL工具 pyetl
2020/06/07 Python
HTML5之多线程(Web Worker)
2019/01/02 HTML / CSS
HTC VIVE美国官网:VR虚拟现实眼镜
2018/02/13 全球购物
美国中西部家用医疗设备商店:Med Mart(轮椅、踏板车、升降机等)
2019/04/26 全球购物
入党申请书自我鉴定
2013/10/12 职场文书
应用化学专业职业生涯规划书
2013/12/31 职场文书
物业管理计划书
2014/01/10 职场文书
自行车广告词大全
2014/03/21 职场文书
党的群众路线对照检查材料
2014/08/27 职场文书
新员工试用期自我评价
2015/03/10 职场文书
狼牙山五壮士观后感
2015/06/09 职场文书
公安干警正风肃纪心得体会
2016/01/15 职场文书