Python Program - Represent enum
here's a Python program that represents an enum
:
# Import the Enum class from the enum module from enum import Enum # Define an enumeration of colors class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 # Access the values of the enumeration print(Color.RED) print(Color.GREEN.value) print(list(Color))Source:www.theitroad.com
In this program, we first import the Enum
class from the enum
module.
We then define an enumeration of colors called Color
, with three possible values: RED
, GREEN
, and BLUE
. Each value is represented as an instance of the Color
class, with a unique integer value (1
, 2
, and 3
, respectively).
We can access the values of the enumeration using dot notation. For example, Color.RED
returns the RED
value, and Color.GREEN.value
returns the integer value 2
.
We can also iterate over the values of the enumeration using the list()
function. In this example, list(Color)
returns a list containing all the values of the Color
enumeration: [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
.
Note that enumerations are useful for representing a fixed set of values that don't change at runtime. They can be used to improve code readability and prevent errors caused by using arbitrary integer values that have no meaning.