Discussion on enumeration of Python Enum
- 2020-06-03 07:17:36
- OfStack
Enumeration is a common feature. Take a look at Python's enumeration.
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
Definition of enumeration
First, define the enumeration to import the enum module.
Enumeration is defined with the class keyword and inherits the Enum class.
Note:
When defining an enumeration, member names are not allowed to repeat
By default, different member values are allowed to be the same. But for two members with the same value, the name of the second member is treated as an alias for the first
If members with the same value exist in an enumeration, when an enumeration member is obtained by value, only the first member can be obtained
You cannot define members with the same value if you want to restrict the definition of an enumeration. You can use decorator @ES21en [To import unique module]
for name, member in Month.__members__.items():
print(name, '=>', member, ',', member.value)
We have an enumeration class of type Month, and we can use Month.Jan directly to reference a constant or to enumerate all its members.
There are several ways to access these enumerated types:
Enumerations support iterators that 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.Sun
Mon => Weekday.Mon
Tue => Weekday.Tue
Wed => Weekday.Wed
Thu => Weekday.Thu
Fri => Weekday.Fri
Sat => Weekday.Sat
Enumeration value summary:
Get a member by its name; Get the member by the member value; Gets its name and value through the member.
Note: the members of Enum are singletons (Singleton) and cannot be instantiated or changed.
Enumerations are comparable:
Members can be compared with 1, can be compared with equivalent, can not be compared with size.
Summary :Enum can define a set of related constants in one class, and class is immutable, the members can be directly compared, and enumerations have multiple clock implementation methods.