So I was trying to use enums in python and came upon the following error:
When I was using enum as a tuple and giving it two values, I can't access only one value such as tuple[0]
class Rank(Enum):
ACE = 1
TWO = 2
THREE = 3
FOUR = 4
FIVE = 5
SIX = 6
SEVEN = 7
EIGHT = 8
NINE = 9
TEN = 10
JACK = 11
QUEEN = 12
KING = 13, "King"
print (Rank.KING.value)
and the print is
(13, 'King')
How can I access only one value so I can print 13 or 'King'?
Enum and namedtuple in python as enum and struct in C. In other words, enum s are a way of aliasing values, while namedtuple is a way of encapsulating data by name. The two are not really interchangeable, and you can use enum s as the named values in a namedtuple .
Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over. An enum has the following characteristics.
auto() method, we can get the assigned integer value automatically by just using enum. auto() method. Syntax : enum.auto() Automatically assign the integer value to the values of enum class attributes.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With