When we need to define constants, one way is to use uppercase variables to define integers, such as months
JAN = 1 FEB = 2 MAR = 3 APR=4 May=5 Jun=6 Jul=7 Aug=8 Sep=9 Oct=10 NOV = 11 DEC = 12
The advantage is simplicity, the disadvantage is the type int, and it is still a variable.
A better way is to define a class type for such an enumeration type, and then each constant is a unique instance of class. Python provides the Enum class to implement this function:
from enum import Enum Month=Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
In this way, we get the enumeration class of Month type. You can directly use Month.Jan to reference a constant or enumerate all its members.
>>> Month.Jan <Month.Jan: 1> >>> Month.Feb <Month.Feb: 2>
>>> for name,member in Month.__members__.items(): ... print(name,'=>',member,',',member.value) ... Jan => Month.Jan , 1 Feb => Month.Feb , 2 Mar => Month.Mar , 3 Apr => Month.Apr , 4 May => Month.May , 5 Jun => Month.Jun , 6 Jul => Month.Jul , 7 Aug => Month.Aug , 8 Sep => Month.Sep , 9 Oct => Month.Oct , 10 Nov => Month.Nov , 11 Dec => Month.Dec , 12
The value attribute is an int constant automatically assigned to a member, counting from 1 by default
If you need more precise control over enumeration types, you can derive custom classes from Enum
from enum import Enum,unique @unique class Weekday(Enum): Sun=0 Mon=1 Tue=2 Wed=3 Thu=4 Fri=5 Sat=6
Decorator unique ensures no repetition
There are several ways to access these enumeration values
>>> 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
It can be seen that enumeration constants can be referenced with member names and obtained directly from the value.
Practice
Changing Student's gender property to enumeration type can avoid using strings
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 bart=Student('Bart',Gender.Male)