¿Cómo crear un enum en Python?
Necesitamos importar la clase enum
y dentro de ella el método Enum
ya que no existen enums de forma nativa en Python.
from enum import Enum
class Season(Enum):
SPRING = 1
SUMMER = 2
AUTUMN = 3
WINTER = 4
# printing enum member as string
print(Season.SPRING)
# printing name of enum member using "name" keyword
print(Season.SPRING.name)
# printing value of enum member using "value" keyword
print(Season.SPRING.value)
# printing the type of enum member using type()
print(type(Season.SPRING))
# printing enum member as repr
print(repr(Season.SPRING))
# printing all enum member using "list" keyword
print(list(Season))
# recorriendo todos los valores del enum
for val in Season:
print()
Season.SPRING SPRING 1 <enum 'Season'> <Season.SPRING: 1> [<Season.SPRING: 1>, <Season.SUMMER: 2>, <Season.AUTUMN: 3>, <Season.WINTER: 4>]
from enum import Enum
class Color(Enum):
ROJO = 1
VERDE = 2
AZUL = 3
# Accediendo a los valores del enum
print(Color.ROJO) # Color.ROJO
print(Color.VERDE) # Color.VERDE
print(Color.AZUL) # Color.AZUL
# Comparando valores del enum
print(Color.ROJO == Color.VERDE) # False
print(Color.ROJO == Color.ROJO) # True
# Accediendo al valor entero del enum
print(Color.ROJO.value) # 1
print(Color.VERDE.value) # 2
print(Color.AZUL.value) # 3
Color.ROJO Color.VERDE Color.AZUL False True 1 2 3