In Python, an Enum is a set of symbolic names (members) bound to unique, constant values. These names are called ‘enumerators’. You can define an Enum by using the Enum
class in the enum
module. Here’s an example:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
In this example, we defined a Color
Enum with three members: RED
, GREEN
, and BLUE
. These members are bound to the values 1, 2, and 3 respectively.
You can access the members of an Enum by using the dot notation. For example:
# Accessing the RED member
print(Color.RED)
# Output: Color.RED
You can also use the value
attribute of an Enum member to get its value. For example:
# Accessing the value of the RED member
print(Color.RED.value)
# Output: 1
Enums in Python can be compared using the usual comparison operators, such as ==
, !=
, >
, <
, >=
, and <=
. For example:
# Comparing the value of the GREEN member with the value of the BLUE member
print(Color.GREEN == Color.BLUE)
# Output: False