python枚举类型Enum

  在 Python 中,枚举类型可以通过 enum 模块来实现。enum 模块提供了 Enum 类,用于创建具有命名值的枚举类型。枚举类型的创建方式包括使用类定义、使用函数和使用装饰器。

1.定义一个枚举类

from enum import Enum

class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

  通过使用枚举,我们可以清晰地表示星期的每一天,避免了使用数字或字符串来表示。

2.输出与遍历输出

#输出
print(Weekday)#<enum 'Weekday'>
print(Weekday.MONDAY)#Weekday.MONDAY
print(Weekday.MONDAY.name)#MONDAY
print(Weekday.MONDAY.value)#1

#遍历输出
for day in Weekday:
    print(day)
'''
Weekday.MONDAY
Weekday.TUESDAY
Weekday.WEDNESDAY
Weekday.THURSDAY
Weekday.FRIDAY
Weekday.SATURDAY
Weekday.SUNDAY
'''

3.比较枚举成员

class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    SATURDAY = 6

print(type(Weekday.WEDNESDAY))#<enum 'Weekday'>
today=Weekday.SATURDAY
print(type(today))#<enum 'Weekday'>

# 比较枚举成员
if today == Weekday.WEDNESDAY:
    print("It's SATURDAY!")

print(type(Weekday.SATURDAY.value))#<class 'int'>
print(Weekday.SATURDAY.value)#6

#或者
if 6==Weekday.SATURDAY.value:
    print(Weekday.SATURDAY.value)#6

  实际上判断两个枚举类型是否相等时,是按其值去比较的,假设我们在类中定义MONDAY=1 TUESDAY=1,那么Weekday.MONDAY==Weekday.TUESDAY是成立的。

4.相同枚举值的处理

  在枚举类中,可以有相同值,但是后面的枚举项都是第一个的别名。

class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 1
    WEDNESDAY = 3

print(Weekday.MONDAY)#Weekday.MONDAY
print(Weekday.TUESDAY)#Weekday.MONDAY

5.装饰器@unique

  加入@unique后,不得有重复的value值,否则报错

from enum import unique
@unique
class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 1
    WEDNESDAY = 3

print(Weekday.MONDAY)#报错ValueError: duplicate values found in <enum 'Weekday'>: TUESDAY -> MONDAY

6.auto()函数的使用

  使用 auto() 函数可以让 Enum 自动为成员分配唯一的值。

from enum import Enum, auto

class Weekday(Enum):
    MONDAY = auto()
    TUESDAY = auto()
    WEDNESDAY = auto()
    THURSDAY = auto()
    FRIDAY = auto()
    SATURDAY = auto()
    SUNDAY = auto()


for day in Weekday:
    print(day.name,'=',day.value)

'''
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
'''

 

小结:注意无论我们是否加@unique装饰器,我们的枚举类型的name都是不能重复的,比如在类中不能出现MONDAY=1 MONDAY=2;另外,多说一句,我们这里定义的python类中的成员为类成员,可以直接类名.属性名访问的。

 

  若存在不足或错误之处,欢迎指出与点评!

posted @ 2023-12-25 17:44  wancy  阅读(199)  评论(0编辑  收藏  举报