How do I create a constant in Python?

后端 未结 30 3022
既然无缘
既然无缘 2020-11-22 09:07

Is there a way to declare a constant in Python? In Java we can create constant values in this manner:

public static          


        
30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 09:22

    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"
    

    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.


    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
    

提交回复
热议问题