10.1. Enum About
List of finite choices
Enumerations
10.1.1. SetUp
>>> from enum import Enum
10.1.2. Syntax
>>> class Color(Enum):
... RED = 'r'
... GREEN = 'g'
... BLUE = 'b'
10.1.3. Get Name, Value
>>> mycolor = Color('g')
>>>
>>> mycolor
<Color.GREEN: 'g'>
>>>
>>> mycolor.name
'GREEN'
>>>
>>> mycolor.value
'g'
10.1.4. Comparison
>>> mycolor = Color('g')
>>>
>>> mycolor is Color.RED
False
>>>
>>> mycolor is Color.GREEN
True
10.1.5. Iteration
>>> for color in Color:
... print(color)
Color.RED
Color.GREEN
Color.BLUE
10.1.6. Methods
>>> class Color(Enum):
... RED = 'r'
... GREEN = 'g'
... BLUE = 'b'
...
... @classmethod
... def get_favourite(cls):
... return cls.RED
>>> Color.get_favourite()
<Color.RED: 'r'>
10.1.7. Enum vs. Dict
Enum:
>>> class Color(Enum):
... RED = 'r'
... GREEN = 'g'
... BLUE = 'b'
...
>>>
>>> Color.RED
<Color.RED: 'r'>
>>>
>>> Color('r')
<Color.RED: 'r'>
Dict:
>>> color = {
... 'RED': '#FF0000',
... 'GREEN': '#00FF00',
... 'BLUE': '#0000FF',
... }
>>>
>>> color['RED']
'#FF0000'
>>>
>>> color['#FF0000']
Traceback (most recent call last):
KeyError: '#FF0000'
>>>
>>> tmp = {v:k for k,v in color.items()}
>>> tmp['#FF0000']
'RED'
10.1.8. Use Case - 1
HTML Colors
>>> class Color(Enum):
... AQUA = '#00FFFF'
... BLACK = '#000000'
... BLUE = '#0000ff'
... FUCHSIA = '#FF00FF'
... GRAY = '#808080'
... GREEN = '#008000'
... LIME = '#00ff00'
... MAROON = '#800000'
... NAVY = '#000080'
... OLIVE = '#808000'
... PINK = '#ff1a8c'
... PURPLE = '#800080'
... RED = '#ff0000'
... SILVER = '#C0C0C0'
... TEAL = '#008080'
... WHITE = '#ffffff'
... YELLOW = '#FFFF00'