Python实现Const详解

作者:hebedich 时间:2021-06-24 16:18:40 

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,Const
0
投稿

猜你喜欢

  • 关于python字符串方法分类详解

    2023-12-30 22:51:44
  • python 寻找优化使成本函数最小的最优解的方法

    2023-03-02 16:42:39
  • 解析SQL Server数据体系和应用程序逻辑

    2009-01-23 13:58:00
  • 细数JavaScript 一个等号,两个等号,三个等号的区别

    2023-08-25 08:22:09
  • 5个很好的Python面试题问题答案及分析

    2023-05-12 18:45:23
  • 二级联动下拉菜单javascript源码

    2010-03-16 12:32:00
  • 根据选择的checkbox列出选择的值

    2008-07-30 12:56:00
  • python实现单机五子棋

    2021-04-26 05:34:35
  • PHP伪协议基本原理介绍

    2023-05-30 00:24:11
  • go Cobra命令行工具入门教程

    2023-06-24 18:27:12
  • Oracle 管道 解决Exp/Imp大量数据处理问题

    2009-07-12 18:31:00
  • 一个较新的ASP后门服务端实现代码

    2011-02-16 10:41:00
  • HTML编写小经验

    2011-06-14 09:43:14
  • 一篇文章彻底搞懂Python切片操作

    2021-10-11 18:23:07
  • Python中OpenCV Tutorials 20  高动态范围成像的实现步骤

    2022-04-02 07:24:20
  • Python更换pip源方法过程解析

    2022-01-20 08:00:58
  • 成功实现ajax,xmlhttp跨域访问(php,asp,jsp)

    2008-02-13 18:40:00
  • Oracle数据仓库的分层管理器解决方案开发者网络Oracle

    2010-07-16 13:08:00
  • python智联招聘爬虫并导入到excel代码实例

    2023-09-28 14:18:00
  • tornado捕获和处理404错误的方法

    2023-11-27 11:03:36
  • asp之家 网络编程 m.aspxhome.com