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

首頁(yè) > 編程 > Python > 正文

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

2020-02-23 06:20:54
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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

定義const類(lèi)如下

代碼如下:
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]可以獲取一個(gè)模塊對(duì)象,并可以通過(guò)該對(duì)象獲取模塊的屬性,這兒使用了sys.modules向系統(tǒng)字典中注入了一個(gè)Const對(duì)象從而實(shí)現(xiàn)了在執(zhí)行import const時(shí)實(shí)際獲取了一個(gè)Const實(shí)例的功能,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()這條語(yǔ)句將系統(tǒng)已加載的模塊列表中的const替換為了Const(),即一個(gè)Const實(shí)例

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

代碼如下:
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'

這兒首先需要說(shuō)明python中import module和from module import的區(qū)別

import module只是將module的name加入到目標(biāo)文件的局部字典中,不需要對(duì)module進(jìn)行解釋
from module import xxx需要將module解釋后加載至內(nèi)存中,再將相應(yīng)部分加入目標(biāo)文件的局部字典中
python模塊中的代碼僅在首次被import時(shí)被執(zhí)行一次
from project.utils import const時(shí),發(fā)生了sys.modules[name] = Const(),此時(shí)const模塊已經(jīng)加載進(jìn)入內(nèi)存,系統(tǒng)字典中也已經(jīng)有了Const對(duì)象,隨后既可以使用Const實(shí)例了

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

代碼如下:
from project.apps.project_consts import const
print const.MAIL_PROTO_IMAP

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 汉阴县| 紫阳县| 阿图什市| 镇雄县| 贵溪市| 电白县| 长治县| 衡水市| 留坝县| 青浦区| 齐河县| 泸州市| 栾城县| 于都县| 遵义市| 改则县| 新龙县| 闽侯县| 呼和浩特市| 镇江市| 郑州市| 买车| 惠州市| 乐陵市| 根河市| 塘沽区| 泽普县| 安康市| 宣化县| 云浮市| 建瓯市| 兰州市| 贞丰县| 新乡县| 长宁区| 江山市| 芷江| 怀柔区| 潼关县| 曲水县| 成都市|