Python中实现常量(Const)功能

yipeiwu_com5年前Python基础

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的区别

1.import module只是将module的name加入到目标文件的局部字典中,不需要对module进行解释
2.from module import xxx需要将module解释后加载至内存中,再将相应部分加入目标文件的局部字典中
3.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通过win32 COM实现Word文档的写入与保存方法

使用Python通过win32 COM实现Word文档的写入与保存方法

通过win32 COM接口实现软件的操作本质上来看跟直接操作软件一致,这跟我之前经常用的通过各种扩展的组件或者库实现各种文件的处理有较大的差异。如果有过Windows下使用Word的经历...

python实现图片插入文字

python实现图片插入文字

本文实例为大家分享了python图片插入文字的具体代码,供大家参考,具体内容如下 问题 如何在图片中插入大量文字并且自动换行 效果 原始图 效果图 注明 若需要写入中文请使用中文字体...

仅用50行代码实现一个Python编写的计算器的教程

 简介 在这篇文章中,我将向大家演示怎样向一个通用计算器一样解析并计算一个四则运算表达式。当我们结束的时候,我们将得到一个可以处理诸如 1+2*-(-3+2)/5.6+3样式的...

Python ldap实现登录实例代码

下面一段代码是小编给大家介绍的Python ldap实现登录实例代码,一起看看吧 ldap_config = { 'ldap_path': 'ldap://xx.xx.xx.xx...

python文件写入write()的操作

本文实例为大家分享了python文件写入write()的操作的具体代码,供大家参考,具体内容如下 filename = 'pragramming.txt' with open(f...