有没有办法在Python中声明一个常量?在Java中,我们可以这样创建常量值:
public static final String CONST_NAME = "Name";Python中上述Java常量声明的等价物是什么?
发布于 2010-04-21 20:21:55
不没有。在Python中,不能将变量或值声明为常量。只是不要改变它。
如果您在某个类中,则等效项为:
class Foo(object):
CONST_NAME = "Name"如果不是,它只是
CONST_NAME = "Name"但是您可能想看一下Alex Martelli编写的代码片段Constants in Python。
从Python3.8开始,有一个typing.Final变量注释,它会告诉静态类型检查器(比如mypy)你的变量不应该被重新赋值。这是与Java的final最接近的等价物。但是,it 实际上并不会阻止重新分配
from typing import Final
a: Final = 1
# Executes fine, but mypy will report an error if you run mypy on this:
a = 2发布于 2010-04-22 11:39:39
在其他语言中没有const关键字,但是可以创建一个属性,即有一个"getter function"来读取数据,但是没有"setter function"来重写数据。这实际上保护了标识符不会被更改。
下面是一个使用class属性的替代实现:
请注意,对于想要了解常量的读者来说,代码远非易事。请参阅下面的说明
def constant(f):
def fset(self, value):
raise TypeError
def fget(self):
return f()
return property(fget, fset)
class _Const(object):
@constant
def FOO():
return 0xBAADFACE
@constant
def BAR():
return 0xDEADBEEF
CONST = _Const()
print CONST.FOO
##3131964110
CONST.FOO = 0
##Traceback (most recent call last):
## ...
## CONST.FOO = 0
##TypeError: None代码说明:
expression.
constant,并使用它来构造一个“TypeError”-一个只返回expression.
constantTypeError,以快速定义只读属性。以及其他一些更老式的方式:
(代码相当棘手,下面有更多解释)
class _Const(object):
@apply
def FOO():
def fset(self, value):
raise TypeError
def fget(self):
return 0xBAADFACE
return property(**locals())
CONST = _Const()
print CONST.FOO
##3131964110
CONST.FOO = 0
##Traceback (most recent call last):
## ...
## CONST.FOO = 0
##TypeError: None请注意,@apply修饰符似乎已被弃用。
使用内置的property函数来构造一个可以是“”或“
property函数的前两个参数分别命名为fset和fget。property函数发布于 2010-04-21 21:06:32
在Python中,人们使用命名约定,例如私有方法使用__method,保护方法使用_method,而不是使用语言强制执行某些东西。
因此,以同样的方式,您可以简单地将常量声明为所有大写,例如
MY_CONSTANT = "one"如果您希望这个常量永远不会改变,您可以挂钩到属性访问并执行一些技巧,但更简单的方法是声明一个函数
def MY_CONSTANT():
return "one"唯一的问题是你必须做MY_CONSTANT(),但是在python中MY_CONSTANT = "one" (通常)是正确的方式。
您还可以使用namedtuple创建常量:
>>> from collections import namedtuple
>>> Constants = namedtuple('Constants', ['pi', 'e'])
>>> constants = Constants(3.14, 2.718)
>>> constants.pi
3.14
>>> constants.pi = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attributehttps://stackoverflow.com/questions/2682745
复制相似问题