Enum for Python and enum for python
Enumeration is a common function. Let's look at Python enumeration.
from enum import EnumMonth = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
Enumeration Definition
Note:
Repeated Member names are not allowed when enumeration is defined.
By default, different Member values are allowed to be the same. However, for two members with the same value, the name of the second member is treated as the alias of the first member.
If a member with the same value exists in the enumeration, only the first member can be obtained when the enumerated member is obtained through the value.
If you want to restrict the definition of enumeration, you cannot define members with the same value. You can use the decorator @ unique to import the unique module]
for name, member in Month.__members__.items(): print(name, '=>', member, ',', member.value)
Then we getMonthType enumeration class, which can be directly usedMonth.JanTo reference a constant or enumerate all its members.
There are several methods to access these enumeration types:
Enumeration supports the iterator to 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 enumerated values:
Obtain members by their names;Obtain members by using the member value;Obtain the name and value of a member.
Note:EnumAre Singleton members and cannot be instantiated or changed.
Enumeration can be compared:
For example, you can compare the identities of members,Equality comparison,Cannot compare the size.
Summary:EnumA group of constants can be defined in a class, and the class is immutable, and the Members can be directly compared, and there are multiple implementation methods for enumeration.