How do I create a constant in Python?

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

    In Python, constants do not exist, but you can indicate that a variable is a constant and must not be changed by adding CONST_ to the start of the variable name and stating that it is a constant in a comment:

    myVariable = 0
    CONST_daysInWeek = 7    # This is a constant - do not change its value.   
    CONSTANT_daysInMonth = 30 # This is also a constant - do not change this value.
    

    Alternatively, you may create a function that acts like a constant:

    def CONST_daysInWeek():
        return 7;
    

提交回复
热议问题