How do I create a constant in Python?

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

    We can create a descriptor object.

    class Constant:
      def __init__(self,value=None):
        self.value = value
      def __get__(self,instance,owner):
        return self.value
      def __set__(self,instance,value):
        raise ValueError("You can't change a constant")
    

    1) If we wanted to work with constants at the instance level then:

    class A:
      NULL = Constant()
      NUM = Constant(0xFF)
    
    class B:
      NAME = Constant('bar')
      LISTA = Constant([0,1,'INFINITY'])
    
    >>> obj=A()
    >>> print(obj.NUM)  #=> 255
    >>> obj.NUM =100
    
    Traceback (most recent call last):
    File "", line 1, in 
    ValueError: You can't change a constant
    

    2) if we wanted to create constants only at the class level, we could use a metaclass that serves as a container for our constants (our descriptor objects); all the classes that descend will inherit our constants (our descriptor objects) without any risk that can be modified.

    # metaclass of my class Foo
    class FooMeta(type): pass
    
    # class Foo
    class Foo(metaclass=FooMeta): pass
    
    # I create constants in my metaclass
    FooMeta.NUM = Constant(0xff)
    FooMeta.NAME = Constant('FOO')
    
    >>> Foo.NUM   #=> 255
    >>> Foo.NAME  #=> 'FOO'
    >>> Foo.NUM = 0 #=> ValueError: You can't change a constant
    

    If I create a subclass of Foo, this class will inherit the constant without the possibility of modifying them

    class Bar(Foo): pass
    
    >>> Bar.NUM  #=> 255
    >>> Bar.NUM = 0  #=> ValueError: You can't change a constant
    

提交回复
热议问题