Enumeration is a common feature to look at the Python enumeration.
from enum Import enummonth = enum (' Month ', (' Jan ', ' Feb ', ' Mar ', ' April ', ' may ', ' June ', ' Jul ', ' April ', ' Sep ', ' Oct ', ' Nov ', ' Dec '))
@uniqueclass Weekday (Enum): Sun = 0 # Sun's value is set to 0 Mon = 1Tue = 2Wed = 3Thu = 4Fri = 5Sat = 6
For name, member in Month.__members__.items (): print (name, ' = = ', member, ', ', Member.value)
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 membership is obtained when the enumeration member is obtained by a 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"
For name, member in Month.__members__.items (): print (name, ' = = ', member, ', ', Member.value)
We get an Month enumeration class of type, which can be used directly Month.Jan to reference a constant, or to enumerate all its members.
There are several ways to access these enumeration types:
Enumeration supports iterators that can traverse enumeration members
>>> 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
Summary of enumeration values:
Get members by name of member; get members by member values; gets its name and value through the member.
Note: Enum The members are Singleton (Singleton) and cannot be instantiated and cannot be changed.
Enumerations can be compared:
The members can be compared with each other, and can not be compared in size.
Summary: Enum a set of related constants can be defined in a class, and the class is immutable, and the members can be compared directly, and the enumeration has a number of implementation methods.