如何在Python中创建常量? [英] How do I create a constant in Python?

查看:140
本文介绍了如何在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常量,作者是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中创建常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆