How do I create a constant in Python?

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

    There's no const keyword as in other languages, however it is possible to create a Property that has a "getter function" to read the data, but no "setter function" to re-write the data. This essentially protects the identifier from being changed.

    Here is an alternative implementation using class property:

    Note that the code is far from easy for a reader wondering about constants. See explanation below

    def constant(f):
        def fset(self, value):
            raise TypeError
        def fget(self):
            return f()
        return property(fget, fset)
    
    class _Const(object):
        @constant
        def FOO():
            return 0xBAADFACE
        @constant
        def BAR():
            return 0xDEADBEEF
    
    CONST = _Const()
    
    print CONST.FOO
    ##3131964110
    
    CONST.FOO = 0
    ##Traceback (most recent call last):
    ##    ...
    ##    CONST.FOO = 0
    ##TypeError: None
    

    Code Explanation:

    1. Define a function constant that takes an expression, and uses it to construct a "getter" - a function that solely returns the value of the expression.
    2. The setter function raises a TypeError so it's read-only
    3. Use the constant function we just created as a decoration to quickly define read-only properties.

    And in some other more old-fashioned way:

    (The code is quite tricky, more explanations below)

    class _Const(object):
        @apply
        def FOO():
            def fset(self, value):
                raise TypeError
            def fget(self):
                return 0xBAADFACE
            return property(**locals())
    
    CONST = _Const()
    
    print CONST.FOO
    ##3131964110
    
    CONST.FOO = 0
    ##Traceback (most recent call last):
    ##    ...
    ##    CONST.FOO = 0
    ##TypeError: None
    

    Note that the @apply decorator seems to be deprecated.

    1. To define the identifier FOO, firs define two functions (fset, fget - the names are at my choice).
    2. Then use the built-in property function to construct an object that can be "set" or "get".
    3. Note hat the property function's first two parameters are named fset and fget.
    4. Use the fact that we chose these very names for our own getter & setter and create a keyword-dictionary using the ** (double asterisk) applied to all the local definitions of that scope to pass parameters to the property function

提交回复
热议问题