Programming Language/Python3
Python Define Constants
아기 요다
2021. 10. 25. 18:00
how-do-i-create-a-constant-in-python
원본 글 번역한거
Question
Java
에서는 아래의 방법으로 상수를 선언할 수 있는데, Python
에서는 어떤 방법으로 상수를 선언할 수 있니?
public static final String CONST_NAME = "Name";
Python
에서 위의 Java
의 상수 선언과 동일한 것은 무엇이니?
Answer
없어. 넌 Python
에서 상수로서 변수를 선언할 수 없어. 그냥 바꾸지 않아야해.
만약 네가 클래스 내에서, 동일하게 선언하고자 한다면:
class Foo(object):
CONST_NAME = "Name"
아니라면, 그냥
CONST_NAME = "Name"
But you might want to have a look at the code snippet Constants in Python by Alex Martelli.
As of Python 3.8, there's a [typing.Final](https://docs.python.org/3/library/typing.html#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
note
- 번역은 위의 url 읽고 마저 진행하겠음.
- 안하는 중