Enumeration is a commonly used function, 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'))
@uniqueclass Weekday(Enum): Sun = 0 # Sun的value被设定为0 Mon = 1Tue = 2Wed = 3Thu = 4Fri = 5Sat = 6
for name, member in Month.__members__.items(): print(name, '=>', member, ',', member.value)
Definition of enumeration
First, to define an enumeration, import the enum module.
#The enumeration is defined using the class keyword and inherits the Enum class.
Note:
When defining an enumeration, member names are not allowed to be repeated
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 regarded as an alias of the first member
If there are members with the same value in the enumeration , when getting the enumeration members by value, only the first member
<em><span style="font-family: 宋体"> </span></em><span style="font-family: 宋体; font-size: 15px">如果要限制定义枚举时,不能定义相同值的成员。可以使用装饰器@unique【要导入unique模块】</span><span style="font-family: 宋体"><br><br><br></span><em><span style="font-family: 宋体"><br></span></em>
for name, member in Month.__members__.items(): print(name, '=>', member, ',', member.value)
<br>
we get For the Month
type enumeration class, you can directly use Month.Jan
to reference a constant, or to enumerate all its members.
There are several ways to access these enumeration types Method:
The enumeration supports iterators, which can traverse the 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.Sun Mon => Weekday.Mon Tue => Weekday.Tue Wed => Weekday.Wed Thu => Weekday.Thu Fri => Weekday.Fri Sat => Weekday.Sat
Summary of enumeration values:
Get members by their names;Get members by their values;Get their names and values through members.
Note: The members of Enum
are singletons and cannot be instantiated , cannot be changed.
Enumerations are comparable:
Identity comparison can be performed on selected members, can be compared on equal value, cannot be compared on size.
##Summary:EnumYou can define a group of related constants in one In class, class is immutable, and members can be directly compared, and enumerations have multiple implementation methods.
The above is the detailed content of Python enumeration Enum. For more information, please follow other related articles on the PHP Chinese website!