Appearance
Using Enum Classes
When we need to define constants, one way is to use uppercase variables defined with integers. For example, months:
python
JAN = 1
FEB = 2
MAR = 3
...
NOV = 11
DEC = 12
The advantage is simplicity, but the drawback is that the type is int
, and they are still variables.
A better approach is to define a class
type for such enumeration types, where each constant is a unique instance of the class. Python provides the Enum
class to achieve this functionality:
python
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
This way, we obtain an enumeration class of type Month
. You can directly reference a constant using Month.Jan
or iterate through all members:
python
for name, member in Month.__members__.items():
print(name, '=>', member, ',', member.value)
The value
attribute is an automatically assigned int
constant, starting from 1
by default.
If you need more precise control over the enumeration type, you can derive a custom class from Enum
:
python
from enum import Enum, unique
@unique
class Weekday(Enum):
Sun = 0 # The value of Sun is set to 0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
The @unique
decorator helps ensure that there are no duplicate values.
There are several ways to access these enumeration types:
python
>>> day1 = Weekday.Mon
>>> print(day1)
Weekday.Mon
>>> print(Weekday.Tue)
Weekday.Tue
>>> print(Weekday['Tue'])
Weekday.Tue
>>> print(Weekday.Tue.value)
2
>>> print(day1 == Weekday.Mon)
True
>>> print(day1 == Weekday.Tue)
False
>>> print(Weekday(1))
Weekday.Mon
>>> print(day1 == Weekday(1))
True
>>> Weekday(7)
Traceback (most recent call last):
...
ValueError: 7 is not a valid Weekday
>>> for name, member in Weekday.__members__.items():
... print(name, '=>', member)
...
Sun => Weekday.Sun
Mon => Weekday.Mon
Tue => Weekday.Tue
Wed => Weekday.Wed
Thu => Weekday.Thu
Fri => Weekday.Fri
Sat => Weekday.Sat
As seen, you can reference enumeration constants by their member names or directly obtain enumeration constants based on their value
.
Exercise
Modify the gender
attribute of the Student
class to use an enumeration type, which helps avoid using strings:
python
from enum import Enum, unique
class Gender(Enum):
Male = 0
Female = 1
class Student(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
# Test:
bart = Student('Bart', Gender.Male)
if bart.gender == Gender.Male:
print('Test passed!')
else:
print('Test failed!')
Summary
Enum
allows you to define a set of related constants within a class
. The class
is immutable, and its members can be compared directly.