| Accessing Enums | ||||||||
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
# direct access
print(Color.RED)
# access the enum's value
print(Color.GREEN.value)
# lookup enum by value
print(Color(2))
# key lookup
print(Color["RED"])
output
Color.RED 2 Color.GREEN Color.RED |
||||||||
| Benefits to Using Enums | ||||||||
|
||||||||
| Types of Enums | ||||||||
|
||||||||
| Extending Enum Functionality | ||||||||
since an Enum is a class it can have class methods
from enum import Enum
class Weekday(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
def is_weekend(self):
return self in (Weekday.SATURDAY, Weekday.SUNDAY)
print(Weekday.SATURDAY.is_weekend())
print(Weekday.WEDNESDAY.is_weekend())
output
True False |
||||||||
| Custom Values | ||||||||
|
custom values can be added to an enum an enum's value attribute is protected class Color(Enum):
RED = 1, (255, 0, 0)
GREEN = 2, (0, 255, 0)
BLUE = 3, (0, 0, 255)
def __init__(self, value, rgb):
self.value = value # Attribute Error: Cannot set 'value'
self.rgb = rgb
to set the value use the _value_ attribute
class Color(Enum):
RED = 1, (255, 0, 0)
GREEN = 2, (0, 255, 0)
BLUE = 3, (0, 0, 255)
def __init__(self, value, rgb):
self._value_ = value
self.rgb = rgb
print(Color.RED)
print(Color.RED.value)
print(Color.RED.rgb)
output
Color.RED 1 (255, 0, 0) |