How do I create a constant in Python?(如何在 Python 中创建常量?)
问题描述
有没有办法在 Python 中声明一个常量?在 Java 中,我们可以通过这种方式创建常量值:
Is there a way to declare a constant in Python? In Java we can create constant values in this manner:
public static final String CONST_NAME = "Name";
上述Java常量声明在Python中的等价物是什么?
What is the equivalent of the above Java constant declaration in Python?
推荐答案
没有没有.您不能在 Python 中将变量或值声明为常量.只是不要改变它.
No there is not. You cannot declare a variable or value as constant in Python. Just don't change it.
如果您在课堂上,则相当于:
If you are in a class, the equivalent would be:
class Foo(object):
CONST_NAME = "Name"
如果没有,那只是
CONST_NAME = "Name"
但您可能想看看代码片段 Python 中的常量 by Alex Martelli.
But you might want to have a look at the code snippet Constants in Python by Alex Martelli.
从 Python 3.8 开始,有一个 typing.Final 变量注释将告诉静态类型检查器(如 mypy)不应重新分配您的变量.这是最接近 Java 的 final 的等价物.但是,它实际上并不能阻止重新分配:
As of Python 3.8, there's a typing.Final variable annotation that will tell static type checkers (like mypy) that your variable shouldn't be reassigned. This is the closest equivalent to Java's final. However, it does not actually prevent reassignment:
from typing import Final
a: Final = 1
# Executes fine, but mypy will report an error if you run mypy on this:
a = 2
这篇关于如何在 Python 中创建常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Python 中创建常量?
基础教程推荐
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
