首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Python中创建常量?

如何在Python中创建常量?
EN

Stack Overflow用户
提问于 2010-04-21 20:20:19
回答 43查看 1.2M关注 0票数 1.2K

有没有办法在Python中声明一个常量?在Java中,我们可以这样创建常量值:

代码语言:javascript
运行
复制
public static final String CONST_NAME = "Name";

Python中上述Java常量声明的等价物是什么?

EN

Stack Overflow用户

发布于 2017-03-28 00:04:10

您可以在下一个类的帮助下模拟常量变量。一个用法示例:

代码语言:javascript
运行
复制
# 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的常量类不是时,该类受到保护,不会意外地修改序列类型常量。

源代码如下所示。

代码语言:javascript
运行
复制
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)
票数 -1
EN
查看全部 43 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2682745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档