Python實現(xiàn)Const詳解
python語言本身沒有提供const,但實際開發(fā)中經(jīng)常會遇到需要使用const的情形,由于語言本身沒有這種支出,因此需要使用一些技巧來實現(xiàn)這一功能
定義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向系統(tǒng)字典中注入了一個Const對象從而實現(xiàn)了在執(zhí)行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()這條語句將系統(tǒng)已加載的模塊列表中的const替換為了Const(),即一個Const實例
這樣,整個工程需要使用的常量都應(yīng)該定義在一個文件中,如下
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的區(qū)別
import module只是將module的name加入到目標文件的局部字典中,不需要對module進行解釋
from module import xxx需要將module解釋后加載至內(nèi)存中,再將相應(yīng)部分加入目標文件的局部字典中
python模塊中的代碼僅在首次被import時被執(zhí)行一次
from project.utils import const時,發(fā)生了sys.modules[name] = Const(),此時const模塊已經(jīng)加載進入內(nèi)存,系統(tǒng)字典中也已經(jīng)有了Const對象,隨后既可以使用Const實例了
在其他文件中需要使用常量值時,以如下方式調(diào)用
from project.apps.project_consts import const
print const.MAIL_PROTO_IMAP
- 理解PHP5中static和const關(guān)鍵字的區(qū)別
- php面向?qū)ο笕ヂ?(十) final static const關(guān)鍵字的使用
- C++常對象精講_const關(guān)鍵字的用法
- C#基礎(chǔ)知識系列八const和readonly關(guān)鍵字詳細介紹
- 深入探討C#中的const、readonly關(guān)鍵字
- C++類中的static和const用法實例教程
- C++中的類型轉(zhuǎn)換static_cast、dynamic_cast、const_cast和reinterpret_cast總結(jié)
- C++實現(xiàn)動態(tài)分配const對象實例
- C#中const用法詳解
- javascript中typeof操作符和constucor屬性檢測
- C++ const修飾變量和修飾函數(shù)介紹
- 淺談c#中const與readonly區(qū)別
- C++ 中const 類型限定符不兼容問題
- 淺談const變量賦值報錯分析
- 詳解C語言中const關(guān)鍵字的用法
相關(guān)文章
Python實現(xiàn)TXT數(shù)據(jù)轉(zhuǎn)三維矩陣
在數(shù)據(jù)處理和分析中,將文本文件中的數(shù)據(jù)轉(zhuǎn)換為三維矩陣是一個常見的任務(wù),本文將詳細介紹如何使用Python實現(xiàn)這一任務(wù),感興趣的小伙伴可以了解下2024-01-01python中的插值 scipy-interp的實現(xiàn)代碼
這篇文章主要介紹了python中的插值 scipy-interp的實現(xiàn)代碼,需要的朋友可以參考下2018-07-07分享Pandas庫中的一些寶藏函數(shù)transform()
Pandas具有很多強大的功能,transform就是其中之一,利用它可以高效地匯總數(shù)據(jù)且不改變數(shù)據(jù)行數(shù),transform是一種什么數(shù)據(jù)操作?如果熟悉SQL的窗口函數(shù),就非常容易理解了2021-09-09Pandas 重塑(stack)和軸向旋轉(zhuǎn)(pivot)的實現(xiàn)
這篇文章主要介紹了Pandas 重塑(stack)和軸向旋轉(zhuǎn)(pivot)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07