python 枚举类型

在python中枚举是一种类(Enum,IntEnum),存放在enum模块中。枚举类型可以给一组标签赋予一组特定的值。

枚举的特点:

  1. 枚举类中不能存在相同的标签名
  2. 枚举是可迭代的
  3. 不同的枚举标签可以对应相同的值,但它们都会被视为该值对应第一个标签的别名
  4.  如果要限制定义枚举时,不能定义相同值的成员。可以使用装饰器@unique【要导入unique模块】
  5. 枚举成员之间不能进行大小比较,可进行等值和同一性比较
  6. 枚举成员为单例,不可实例化,不可更改

 

在开始前,我们先定义一个枚举类:

from enum import Enum
class Vip(Enum):
    MONDAY = 0
    TUESDAY = 1
    WEDNESDAY = 2
    THURSDAY = 3
    FRIDAY = 4
    SATURDAY = 5
    SUNDAY = 6

 

示例一:获取在枚举类中定义的枚举成员

# 方法一:
print(Vip.MONDAY)
print(type(Vip.MONDAY))
# 方法二
print(Vip['TUESDAY'])
print(type(Vip.TUESDAY))
# 方法三
print(Vip(2))
print(type(Vip(2)))

-------------------
Vip.MONDAY
<enum 'Vip'>
Vip.TUESDAY
<enum 'Vip'>
Vip.WEDNESDAY
<enum 'Vip'>

 

示例二:枚举成员中包含标签名和该标签对应的值

today = Vip.FRIDAY
print('Today is ' + today.name + '. The number of today is ' + str(today.value))

----------------------------------------
Today is FRIDAY. The number of today is 4

 

示例三:包含相同值的枚举类的迭代,默认情况下不会输出别名,但可通过迭代__members__来显示所有成员标签

from enum import Enum
class Week(Enum):
    MONDAY = 0
    TUESDAY = 1
    FRIDAY = 4
    TODAY = 4    # 以FRIDAY别名的形式存在
for day in Week:
    print(day)
print('******************')
for day in Week.__members__:
    print(day)

----------------------
Week.MONDAY
Week.TUESDAY
Week.FRIDAY
******************
MONDAY
TUESDAY
FRIDAY
TODAY

 

示例四:限定不含相同值的枚举类@unique

from enum import Enum, unique
@unique
class Week(Enum):
    MONDAY = 0
    TUESDAY = 1
    FRIDAY = 4
    TODAY = 4 

--------------------------------------
ValueError: duplicate values found in <enum 'Week'>: TODAY -> FRIDAY

 

posted @ 2019-07-14 15:02  路漫漫我不畏  阅读(30149)  评论(0编辑  收藏  举报