How do I create a constant in Python?

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

    I would make a class that overrides the __setattr__ method of the base object class and wrap my constants with that, note that I'm using python 2.7:

    class const(object):
        def __init__(self, val):
            super(const, self).__setattr__("value", val)
        def __setattr__(self, name, val):
            raise ValueError("Trying to change a constant value", self)
    

    To wrap a string:

    >>> constObj = const("Try to change me")
    >>> constObj.value
    'Try to change me'
    >>> constObj.value = "Changed"
    Traceback (most recent call last):
       ...
    ValueError: Trying to change a constant value
    >>> constObj2 = const(" or not")
    >>> mutableObj = constObj.value + constObj2.value
    >>> mutableObj #just a string
    'Try to change me or not'
    

    It's pretty simple, but if you want to use your constants the same as you would a non-constant object (without using constObj.value), it will be a bit more intensive. It's possible that this could cause problems, so it might be best to keep the .value to show and know that you are doing operations with constants (maybe not the most 'pythonic' way though).

提交回复
热议问题