When we need to define constants, one way is to use uppercase variables to define them by integers, such as the month:
12 3
The advantage is simple, the disadvantage is that the type is int , and is still a 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 Enum classes to implement this functionality:
from enumImport Enummonth= Enum ('Month', ('Jan','Feb','Mar','APR',' May','June','Jul',' the','Sep','Oct','Nov','Dec'))
valueproperty is a constant that is automatically assigned to a member int , and is counted from the beginning by default 1 .
If you need to control the enumeration type more precisely, you can Enum derive the custom class from:
from enum import Enum, Unique@unique class Weekday (Enum): 0 # Sun's value is set to 0 1 2345 6
@uniqueAdorners 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']) 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 (7Traceback (most recent): ... ValueError:7 isNot a valid Weekday>>> forName, memberinchweekday.__members__.items (): .... Print (name,'=', member) ... Sun=Weekday.sunmon=Weekday.montue=weekday.tuewed=Weekday.wedthu=Weekday.thufri=Weekday.frisat= Weekday.sat
Visible, you can either reference the enumeration constant with the member name, or you can get the enumeration constant directly based on the value.
Summary
EnumA set of related constants can be defined in a class, and the class is immutable, and members can be compared directly.
26 Using enum Classes