当前位置: 移动技术网 > IT编程>脚本编程>Python > Python中实现常量(Const)功能

Python中实现常量(Const)功能

2019年03月23日  | 移动技术网IT编程  | 我要评论

手足疾病王根会,朱佳煜的父母资料,空运费用

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网