Python中實現常量(Const)功能

來源:互聯網
上載者:User
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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.