Python实现Const详解

yipeiwu_com6年前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的区别

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自定义函数实现一个数的三次方计算方法

python自定义函数实现一个数的三次方计算方法

python自定义函数在运行时,最初只是存在内存中,只有调用时才会触发运行。 def cube_count(a): if is_number(a): return a**...

python调用新浪微博API项目实践

python调用新浪微博API项目实践

因为最近接触到调用新浪微博开放接口的项目,所以就想试试用python调用微博API。 SDK下载地址:http://open.weibo.com/wiki/SDK 代码不多十几K,完全可...

对python中的six.moves模块的下载函数urlretrieve详解

对python中的six.moves模块的下载函数urlretrieve详解

实验环境:windows 7,anaconda 3(python 3.5),tensorflow(gpu/cpu) 函数介绍:所用函数为six.moves下的urllib中的函数,调用如...

python3 selenium自动化测试 强大的CSS定位方法

ccs的优点:css相对xpath语法比xpath简洁,定位速度比xpath快 css的缺点:css不支持用逻辑运算符来定位,而xpath支持。css定位语法形式多样,相对xpath比较...

python解析yaml文件过程详解

YAML语法规则: http://www.ibm.com/developerworks/cn/xml/x-cn-yamlintro/ 下载PyYAML: http://www.yaml....