Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

python - 如何在Python中创建常量?(How do I create a constant in Python?)

Is there a way to declare a constant in Python?

(有没有办法在Python中声明常量?)

In Java we can create constant values in this manner:

(在Java中,我们可以按以下方式创建常量值:)

public static final String CONST_NAME = "Name";

What is the equivalent of the above Java constant declaration in Python?

(Python中上述Java常量声明的等效项是什么?)

  ask by zfranciscus translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No there is not.

(不,那里没有。)

You cannot declare a variable or value as constant in Python.

(您无法在Python中将变量或值声明为常量。)

Just don't change it.

(只是不要更改它。)

If you are in a class, the equivalent would be:

(如果您在上课,则等效项为:)

class Foo(object):
    CONST_NAME = "Name"

if not, it is just

(如果不是,那只是)

CONST_NAME = "Name"

But you might want to have a look at the code snippet Constants in Python by Alex Martelli.

(但是您可能想看看Alex Martelli编写的Python中的代码片段Constants 。)


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.

(从Python 3.8开始,有一个typing.Final变量注释将告诉静态类型检查器(如mypy)不应重新分配您的变量。)

This is the closest equivalent to Java's final .

(这与Java的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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...