日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Python中實現常量(Const)功能

系統 2441 0

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


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 怀仁县| 石首市| 商丘市| 拉萨市| 开原市| 新竹县| 邮箱| 丰原市| 广安市| 德格县| 喀什市| 陆河县| 留坝县| 华宁县| 六安市| 镇宁| 英山县| 和田县| 林西县| 嘉义市| 涿鹿县| 高青县| 万州区| 临洮县| 大英县| 东兰县| 石景山区| 祁东县| 荔浦县| 绥阳县| 陕西省| 刚察县| 泰安市| 鹰潭市| 怀安县| 台湾省| 麻江县| 正镶白旗| 旬邑县| 当涂县| 原平市|