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

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小技巧分享

获得当前机器的名字: 复制代码 代码如下: def hostname():         sys = os.nam...

用python找出那些被“标记”的照片

用python找出那些被“标记”的照片

源码传送门 环境准备 下面的两个第三方模块都可以直接通过pip快速安装,这里使用py36作为运行环境。 python3.6 requests exifread 思路...

Python实现单词翻译功能

Python实现单词翻译功能

      在进行英文文献阅读时,经常会出现一些不认识的单词,但对于一些pdf阅读器,比如Foxit阅读器使用翻译功能需要点击(Extr...

django2.0扩展用户字段示例

创建新项目,及应用 django-admin startproject myproj cd myproj python manage.py startapp myapp 自定义 U...

Python实现PS图像明亮度调整效果示例

Python实现PS图像明亮度调整效果示例

本文实例讲述了Python实现PS图像明亮度调整效果。分享给大家供大家参考,具体如下: 这里用 Python 实现 PS 图像调整中的明度调整: 我们知道,一般的非线性RGB亮度调整只是...