This article mainly introduces the use of enumeration classes in Python, for more information, see: Python Learning Guide
When we need to define constants, one way is to use uppercase variables to define them by integers, such as the month:
=1=2=3=11=12
The advantage is simple, OK is the type is int
, and still is the variable.
A better approach 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
ability to implement this feature:
fromimport= Enum('Month', ('Jan''Feb''Mar''Apr''May''Jun''Jul''Aug''Sep''Oct''Nov''Dec'))
This gives us the Month
enumeration value of the type, which can be used directly Month.Jan
to reference a constant, or to enumerate all its members:
forin Month.__members__.items(): print'=>'',', member.value)
value
property is automatically assigned to a member int
constant, which is counted by default from the 1
start.
If you need to control the enumeration type more precisely, you can Enum
derive the custom class from:
@uniqueclass Weekday(Enum): =0 =1 =2 =3 =4 =5 =6
@unique
Adorners can help us check that there are no duplicate values
There are several ways to access these enumeration types:
>>>Day1=Weekday.mon>>> Print(Day1) Weekday.mon>>> Print(Weekday.tue) Weekday.tue>>> Print(weekday[' Tue '].name) 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 (7Traceback (most recent): ...ValueError:7 is notA valid Weekday>>> forName, memberinchWeekday.__members__.items (): ...Print(Name,' = ', member) ... Sun=Weekday.sunmon=Weekday.montue=Weekday.tuewed=Weekday.wedthu=Weekday.thufri=Weekday.frisat=Weekday.sat
Python enumeration class