const’s interpretation
- You guess
The python language itself does not provide const, but const is often encountered in actual development, and since the language itself does not have such expenditure, some tricks are needed to achieve this function。
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
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’
from project.utils import const时,发生了sys.modules[name] = Const(),此时const模块已经加载进入内存。