Enumeration Enum and pythonenum in 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
First, import the enum module to define enumeration.
The class keyword is used for enumeration definition to inherit the Enum class.
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)
We get an enumeration class of the Month type. You can use Month. Jan to 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)>>> 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:
Get a member by the member name, get a member by the member value, and get its name and value through the member.
Note: Enum members are Singleton members and cannot be instantiated or changed.
Enumeration can be compared:
For example, a user can perform the same identity comparison, which can be equivalent comparison, but cannot compare the size.
Summary:Enum can define a set of related constants in a class, and the class is not changeable, and the Members can be directly compared, and there are multiple implementation methods for enumeration.
In the above discussion, the Python enumeration Enum is all the content that I have shared with you. I hope to give you a reference, and I hope you can provide more support to the customer's house.