In the following article we will look at what is
enumeration classes in Python。 Find out what is
Python Enumeration class, and what the Python enumeration classes can do in Python programming.
Definition of enumeration
First, define the enumeration to import into the enum module.
Enumeration definitions inherit the enum class with the class keyword.
Attention:
Member names are not allowed to repeat when defining enumerations
By default, different member values allow the same. But two members of the same value, the name of the second member is treated as the alias of the first member
If a member of the same value exists in the enumeration, only the first member is obtained when the enumeration member is obtained by value
If you want to restrict defining enumerations, you cannot define members of the same value. You can use the adorner @unique "to import a unique module"
When we need to define constants, one way is to use uppercase variables to define them by integers, such as the month:
JAN = 1FEB = 2MAR = 3...NOV = 11DEC = 12
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 an enum class to implement this function:
from enum Import enummonth = enum (' Month ', (' Jan ', ' Feb ', ' Mar ', ' April ', ' may ', ' June ', ' Jul ', ' April ', ' Sep ', ' Oct ', ' Nov ', ' Dec '))
This gives us an enumeration class of type month that can be used to refer to a constant using Month.jan, or to enumerate all its members:
For name, member in Month.__members__.items (): print (name, ' = = ', member, ', ', Member.value)
The Value property is an int constant that is automatically assigned to a member, and is counted by default starting at 1.
If you need more precise control over the enumeration type, you can derive the custom class from the enum:
From enum import enum, Unique@uniqueclass Weekday (enum): Sun = 0 # Sun's value is set to 0 Mon = 1 Tue = 2 Wed = 3< C5/>thu = 4 Fri = 5 Sat = 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 ')) 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.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.