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?
JavaScript
x
29
29
1
class Colors(Enum):
2
white = (255, 255, 255)
3
black = (0, 0, 0)
4
red = (255, 0, 0)
5
green = (0, 255, 0)
6
blue = (0, 0, 255)
7
yellow = (255, 255, 0)
8
9
10
class ItemColors(Enum):
11
empty = Colors.white
12
food = Colors.green
13
poison = Colors.red
14
agent = Colors.blue
15
16
17
class Items(Enum):
18
empty = 0
19
food = 1
20
poison = 2
21
agent = 3
22
23
items = [0, 0, 3, 2]
24
25
26
def get_item_color(item):
27
color = ItemColors[Items(item)._name_].value.value
28
return color
29
Advertisement
Answer
Building on @brni’s answer, I came up with a smoother solution:
JavaScript
1
32
32
1
class Colors(Enum):
2
white = (255, 255, 255)
3
black = (0, 0, 0)
4
red = (255, 0, 0)
5
green = (0, 255, 0)
6
blue = (0, 0, 255)
7
yellow = (255, 255, 0)
8
9
10
class Items(Enum):
11
empty = 0
12
food = 1
13
poison = 2
14
agent = 3
15
16
item_colors = {
17
Items.empty: Colors.white,
18
Items.food: Colors.green,
19
Items.poison: Colors.red,
20
Items.agent: Colors.blue
21
}
22
23
items = [0, 0, 3, 2]
24
25
26
def get_item_color(item):
27
color = item_colors[Items(item)].value
28
return color
29
30
for item in items:
31
print(get_item_color(item))
32