国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Python實(shí)現(xiàn)Const

2019-11-14 17:23:53
字體:
供稿:網(wǎng)友

Python實(shí)現(xiàn)const

Python實(shí)現(xiàn)const

python語言本身沒有提供const,但實(shí)際開發(fā)中經(jīng)常會遇到需要使用const的情形,由于語言本身沒有這種支出,因此需要使用一些技巧來實(shí)現(xiàn)這一功能

定義const類如下

import sysclass 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 Nonesys.modules[__name__] = Const()

使用sys.modules[name]可以獲取一個模塊對象,并可以通過該對象獲取模塊的屬性,這兒使用了sys.modules向系統(tǒng)字典中注入了一個Const對象從而實(shí)現(xiàn)了在執(zhí)行import const時實(shí)際獲取了一個Const實(shí)例的功能,sys.module在文檔中的描述如下

sys.modulesThis 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()這條語句將系統(tǒng)已加載的模塊列表中的const替換為了Const(),即一個Const實(shí)例

這樣,整個工程需要使用的常量都應(yīng)該定義在一個文件中,如下

from PRoject.utils import constconst.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的區(qū)別

  • import module只是將module的name加入到目標(biāo)文件的局部字典中,不需要對module進(jìn)行解釋
  • from module import xxx需要將module解釋后加載至內(nèi)存中,再將相應(yīng)部分加入目標(biāo)文件的局部字典中
  • python模塊中的代碼僅在首次被import時被執(zhí)行一次

from project.utils import const時,發(fā)生了sys.modules[name] = Const(),此時const模塊已經(jīng)加載進(jìn)入內(nèi)存,系統(tǒng)字典中也已經(jīng)有了Const對象,隨后既可以使用Const實(shí)例了

在其他文件中需要使用常量值時,以如下方式調(diào)用

from project.apps.project_consts import constprint const.MAIL_PROTO_IMAP

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 栾城县| 辽中县| 义乌市| 剑河县| 武陟县| 榕江县| 罗平县| 茂名市| 乌苏市| 毕节市| 乌兰浩特市| 额济纳旗| 手游| 东乌珠穆沁旗| 永平县| 郎溪县| 三穗县| 阿克陶县| 灵璧县| 溧水县| 兰西县| 长乐市| 抚宁县| 南昌市| 清镇市| 灵川县| 将乐县| 湘潭市| 沿河| 巧家县| 宿迁市| 胶州市| 西和县| 寿宁县| 大同县| 柏乡县| 老河口市| 乌鲁木齐县| 泗阳县| 尼木县| 广宗县|