手足疾病王根会,朱佳煜的父母资料,空运费用
python语言本身没有提供const,但实际开发中经常会遇到需要使用const的情形,由于语言本身没有这种支出,因此需要使用一些技巧来实现这一功能
定义const类如下
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()
这样,整个工程需要使用的常量都应该定义在一个文件中,如下
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'
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实例了
在其他文件中需要使用常量值时,以如下方式调用
print const.mail_proto_imap
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
新手学习Python2和Python3中print不同的用法
Python基于os.environ从windows获取环境变量
网友评论