python tuple and enum
With enum.Enum
, the class variable names themselves become the name
attribute of the enumerated attributes of the Enum
instance, so you don't have to make KING
a tuple of value and name:
class Rank(Enum):
King = 13
print(Rank.King.name) # outputs 'King'
print(Rank.King.value) # outputs 13
If you want to name the class variables with capital letters but have their name
values to be mixed-cased, which isn't what Enum
is designed for, you would have to subclass Enum
and override the name
method yourself to customize the behavior:
from enum import Enum, DynamicClassAttribute
class MixedCaseEnum(Enum):
@DynamicClassAttribute
def name(self):
return self._name_.title()
class Rank(MixedCaseEnum):
KING = 13
print(Rank.KING.name) # outputs 'King'
print(Rank.KING.value) # outputs 13
You have the following possibilites to access 13 or "king":
Rank.KING.value[0]
Rank.KING.value[1]
You can just use indexes as you would use them on an array:
>>> KING = 13, 'King'
>>> KING
(13, 'King')
>>> KING[0]
13
>>> KING[1]
'King'
>>>
None of the existing answers explained how you might have three (or more) values in an Enum, if you wanted to.
For example, say the initial questioner wanted (13, "K", "king")
in the Enum, they would do it like this:
class Rank(Enum):
K = 13, "King"
def __init__(self, rank, label):
self.rank = rank
self.label = label
The __init__
takes the values and assigns them to the enum members. This means that Rank.K.rank
returns 13
and Rank.K.label
returns "King"
.
Although it's not strictly needed in this example, it can be useful to store more than key/value pairs on the Enum.
Note that Rank.K.value
still exists, and returns the tuple (13, "King")