Enums in Python
In Python 3.4, Enum
support was added.
How to implement an Enum
Implementing an Enum
in Python is trivial.
1from enum import Enum
2
3
4class PizzaSize(Enum):
5 SMALL = 0
6 MEDIUM = 1
7 LARGE = 2
8
9
10print(PizzaSize.SMALL) # PizzaSize.SMALL
11print(PizzaSize.SMALL.value) # 0
12print(PizzaSize.SMALL.name) # SMALL
As a shortcut, a range
value may be applied:
1from enum import Enum
2
3
4class PizzaSize(Enum):
5 SMALL, MEDIUM, LARGE = range(3)
6
7
8print(PizzaSize.SMALL) # PizzaSize.SMALL
9print(PizzaSize.SMALL.value) # 0
10print(PizzaSize.SMALL.name) # SMALL