3.1. Enum About

  • List of finite choices

  • Enumerations

3.1.1. Syntax

>>> from enum import Enum
>>>
>>>
>>> class Select(Enum):
...     OPTION1 = 1
...     OPTION2 = 2

3.1.2. SetUp

>>> class Color(Enum):
...     RED = '#FF0000'
...     GREEN = '#00FF00'
...     BLUE = '#0000FF'

3.1.3. Switch

>>> mycolor = Color('#00FF00')
>>>
>>> mycolor
<Color.GREEN: '#00FF00'>
>>>
>>> mycolor.name
'GREEN'
>>>
>>> mycolor.value
'#00FF00'

3.1.4. Comparison

>>> mycolor = Color('#00FF00')
>>>
>>> mycolor is Color.RED
False
>>>
>>> mycolor is Color.GREEN
True

3.1.5. Iteration

>>> for color in Color:
...     print(color)
Color.RED
Color.GREEN
Color.BLUE

3.1.6. Methods

>>> class Color(Enum):
...     RED = '#FF0000'
...     GREEN = '#00FF00'
...     BLUE = '#0000FF'
...
...     @classmethod
...     def get_favourite(cls):
...         return cls.RED
>>> Color.get_favourite()
<Color.RED: '#FF0000'>

3.1.7. Use Case - 0x01

  • 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'

3.1.8. Use Case - 0x02

>>> class PTU(Enum):
...     A = 1.23   # VAT 23%
...     B = 1.08   # VAT 8%
...     C = 1.05   # VAT 5%
...     D = 1.00   # VAT 5%
...     E = 1.00   # VAT Exempt
>>>
>>> PLN = 1
>>> shopping_cart = [
...     {'name': 'Bread',   'price': 3.99*PLN, 'ptu': PTU.C},
...     {'name': 'Butter',  'price': 2.69*PLN, 'ptu': PTU.B},
...     {'name': 'Ham',     'price': 5.99*PLN, 'ptu': PTU.A},
...     {'name': 'Cheese',  'price': 4.19*PLN, 'ptu': PTU.B},
... ]
>>> total = sum(product['price'] * product['ptu'].value
...             for product in shopping_cart)
>>> print(f'Total is: {total:.2f} PLN')
Total is: 18.99 PLN