有没有办法在Python中声明一个常量?在Java中,我们可以这样创建常量值:
public static final String CONST_NAME = "Name";Python中上述Java常量声明的等价物是什么?
发布于 2017-03-28 00:04:10
您可以在下一个类的帮助下模拟常量变量。一个用法示例:
# Const
const = Const().add(two=2, three=3)
print 'const.two: ', const.two
print 'const.three: ', const.three
const.add(four=4)
print 'const.four: ', const.four
#const.four = 5 # a error here: four is a constant
const.add(six=6)
print 'const.six: ', const.six
const2 = Const().add(five=5) # creating a new namespace with Const()
print 'const2.five: ', const2.five
#print 'const2.four: ', const2.four # a error here: four does not exist in const2 namespace
const2.add(five=26)当您想要启动一个新的常量命名空间时,调用构造函数。请注意,当Martelli的常量类不是时,该类受到保护,不会意外地修改序列类型常量。
源代码如下所示。
from copy import copy
class Const(object):
"A class to create objects with constant fields."
def __init__(self):
object.__setattr__(self, '_names', [])
def add(self, **nameVals):
for name, val in nameVals.iteritems():
if hasattr(self, name):
raise ConstError('A field with a name \'%s\' is already exist in Const class.' % name)
setattr(self, name, copy(val)) # set up getter
self._names.append(name)
return self
def __setattr__(self, name, val):
if name in self._names:
raise ConstError('You cannot change a value of a stored constant.')
object.__setattr__(self, name, val)https://stackoverflow.com/questions/2682745
复制相似问题