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 t