I have some Enum classes that I want to link up recursively. Looking at the line color = ItemColors[Items(value)._name_].value.value, it seems a bit clunky. Am I misunderstanding something about Enum usage? Is there a better way to do it?
class Colors(Enum):
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
yellow = (255, 255, 0)
class ItemColors(Enum):
empty = Colors.white
food = Colors.green
poison = Colors.red
agent = Colors.blue
class Items(Enum):
empty = 0
food = 1
poison = 2
agent = 3
items = [0, 0, 3, 2]
def get_item_color(item):
color = ItemColors[Items(item)._name_].value.value
return color
Advertisement
Answer
Building on @brni’s answer, I came up with a smoother solution:
class Colors(Enum):
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
yellow = (255, 255, 0)
class Items(Enum):
empty = 0
food = 1
poison = 2
agent = 3
item_colors = {
Items.empty: Colors.white,
Items.food: Colors.green,
Items.poison: Colors.red,
Items.agent: Colors.blue
}
items = [0, 0, 3, 2]
def get_item_color(item):
color = item_colors[Items(item)].value
return color
for item in items:
print(get_item_color(item))