如何在 Python 中声明一个常量?
在 Java 中,我们做到:
public static final String CONST_NAME = "Name";
网友回答:
没有像其他语言那样的关键字,但是可以创建一个属性,该属性具有“getter 函数”来读取数据,但没有“setter 函数”来重写数据。这实质上保护了标识符不被更改。const
下面是使用类属性的替代实现:
请注意,对于想知道常量的读者来说,代码远非易事。请参阅下面的解释。
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(hex(CONST.FOO)) # -> '0xbaadfaceL'
CONST.FOO = 0
##Traceback (most recent call last):
## File "example1.py", line 22, in <module>
## CONST.FOO = 0
## File "example1.py", line 5, in fset
## raise TypeError
##TypeError
代码说明:
constant
constant
以其他一些更老式的方式:
(代码相当棘手,下面有更多解释)
class _Const(object):
def FOO():
def fset(self, value):
raise TypeError
def fget(self):
return 0xBAADFACE
return property(**locals())
FOO = FOO() # Define property.
CONST = _Const()
print(hex(CONST.FOO)) # -> '0xbaadfaceL'
CONST.FOO = 0
##Traceback (most recent call last):
## File "example2.py", line 16, in <module>
## CONST.FOO = 0
## File "example2.py", line 6, in fset
## raise TypeError
##TypeError
property
property
fset
fget
property
网友回答:
您不能在 Python 中将变量或值声明为常量。
为了向程序员表明变量是一个常量,通常用大写字母写它:
CONST_NAME = "Name"
要在常量更改时引发异常,请参阅 Alex Martelli 的 Python 中的常量。请注意,这在实践中并不常用。
从 Python 3.8 开始,有一个变量注释可以告诉静态类型检查器(如 mypy)你的变量不应该被重新分配。这是最接近Java的等价物。但是,它实际上并不阻止重新分配:typing.Final
final
from typing import Final
a: Final[int] = 1
# Executes fine, but mypy will report an error if you run mypy on this:
a = 2
网友回答:
在Python中,人们使用命名约定而不是语言强制执行某些东西,例如私有方法和受保护方法。__method
_method
因此,以同样的方式,您可以简单地将常量声明为所有大写字母,例如:
MY_CONSTANT = "one"
如果你希望这个常量永远不会改变,你可以挂接到属性访问并做一些技巧,但更简单的方法是声明一个函数:
def MY_CONSTANT():
return "one"
唯一的问题是你必须做的任何地方,但同样是Python中的正确方法(通常)。MY_CONSTANT()
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 attribute
模板简介:该模板名称为【如何在 Python 中声明一个常量?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。