How do I create a constant in Python?

后端 未结 30 3023
既然无缘
既然无缘 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:31

    The Pythonic way of declaring "constants" is basically a module level variable:

    RED = 1
    GREEN = 2
    BLUE = 3
    

    And then write your classes or functions. Since constants are almost always integers, and they are also immutable in Python, you have a very little chance of altering it.

    Unless, of course, if you explicitly set RED = 2.

提交回复
热议问题