python设置常量参数,,python设置常量


python设置常量参数


by 伍雪颖

const.py:

class _const:
class ConstError(TypeError) :pass
class ConstCaseError(ConstError) :pass

def __setattr__(self,name,value):
if self.__dict__.has_key(name):
raise self.ConstError,"Can‘t change const.%s" % name
ifnot name.isupper():
raise self.ConstCaseError,‘const name "%s" is not all uppercase‘ % name
self.__dict__[name] = value

import sys
sys.modules[__name__] = _const()

import const
const.MY_CONSTANT = 1
const.MY_SECOND_CONSTANT = 2
const.MY_THIRD_CONSTANT = ‘a‘const.MY_FORTH_CONSTANT =‘b‘

调用:
test.py:

import const

print const.MY_CONSTANT
print const.MY_SECOND_CONSTANT
print const.MY_THIRD_CONSTANTprint const.MY_FORTH_CONSTANT

输出:

python test.py
1
2
ab

python设置常量参数

评论关闭