Introducing new features of Python 3.4 that started with Yesterday's entry. Today is Enum.
This is a feature I've always wanted, so I'm happy with it. In the case of Python, Enum is not a type but a class, and it is an image defined as a class variable of a class that inherits a name / value pair.
As an example, use the Cardsuit featured in Enumeration (Wikipedia). .. First from the definition.
from enum import Enum
class Cardsuit(Enum):
CLUBS = 1
DIAMONDS = 2
HEARTS = 3
SPADES = 4
And when using it, either instantiate the value as an argument or retrieve the class attribute using the name as a key.
#The same value is assigned to the following
card0 = Cardsuit(2)
card1 = Cardsuit['DIAMONDS']
card2 = Cardsuit.DIAMONDS
#When printed normally, it is output in the final format
print(card0, card1, card2) # -> Cardsuit.DIAMONDS Cardsuit.DIAMONDS Cardsuit.DIAMONDS
#Name and value can be retrieved separately
print(card0.name, card0.value) # -> DIAMONDS 2
The Python Enum is --Assign different values to the same name ... NG --Assign the same value to a different name ... OK
However, if you use Enum.unique, you can also NG the second one.
from enum import Enum
#This is OK
class Cardsuit(Enum):
CLUBS = 1
DIAMONDS = 2
HEARTS = 3
SPADES = 4
ALT_SPADES = 4
#This is NG
@unique
class Cardsuit(Enum):
CLUBS = 1
DIAMONDS = 2
HEARTS = 3
SPADES = 4
ALT_SPADES = 4
I was a little surprised that Enums are classes, but that may be the case. For example, define an error code as a name / value pair and add methods to it as needed. I wonder if it will become clearer if I do a little more actual coding.
Recommended Posts