Enumeration is a common feature to look at the Python enumeration.
from enumImport Enummonth= Enum ('Month', ('Jan','Feb','Mar','APR',' May','June','Jul',' the','Sep','Oct','Nov','Dec'))
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 inch Month.__members__.items (): ' = ' ' , ', 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 (7Traceback (most recent): ... ValueError:7 isNot a valid Weekday>>> forName, memberinchweekday.__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 directly compared, and the enumeration has a multi-clock implementation method.
Enum enum for Python