In Python, you can enumerate an
enum
using a for
loop or the enum.Enum
class.Here's an example of using a for
loop to enumerate an enum
:
pythonfrom enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
for color in Color:
print(color)
In this example, the Color
enum
is defined with three values: RED
, GREEN
, and BLUE
. The for
loop iterates over the Color
enum
, printing each Color
value to the console.
Alternatively, you can use the enum.Enum
class to define an enum
and retrieve its values. Here's an example:
pythonfrom enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(list(Color))
In this example, the Color
enum
is defined with three values: RED
, GREEN
, and BLUE
. The list
function is called on the Color
enum
to retrieve a list of its values, which is then printed to the console.
Note that the enum.Enum
class provides additional functionality for defining and working with enums
, such as the ability to compare enum
values and retrieve their names and values.
Comments
Post a Comment