Python

Python基础-23枚举

2022-07-31  本文已影响0人  Surpassme

23 枚举

    枚举是一组符号名称(枚举成员)的集合,枚举成员应该是唯一的、不可变的。

23.1 使用普通类实现枚举类

class basicWeek():
    SUN=0
    MON=1
    TUE=2
    WED=3
    THU=4
    FRI=5
    SAT=6

# 获取值
print(basicWeek.SUN) # 0

    虽然这样也可以实现,但不严谨,也不安全,原因如下所示:

class basicWeek():
    SUN=0
    MON=1
    TUE=2
    WED=3
    THU=4
    FRI=5
    SAT=6
    SUN=7 # 这里会覆盖前面已经定义的值

# 获取值
print(basicWeek.SUN) # 7
# 在外面修改值
basicWeek.SUN=99
# 再次获取的值为修改后的值
print(basicWeek.SUN) # 99

    为了解决这种问题,我们引入枚举类

23.2 枚举类

    在Python中使用枚举类,可以引入内置模块Enum,如下所示:

from enum import Enum

class EnumWeek(Enum):
    SUN = 0
    MON=1
    TUE=2
    WED=3
    THU=4
    FRI=5
    SAT=6

print(EnumWeek.SUN) # EnumWeek.SUN
print(type(EnumWeek.SUN)) # <enum 'EnumWeek'>
print(EnumWeek.SUN.value) # 0
print(EnumWeek(5)) # EnumWeek.FRI
print(type(EnumWeek.SUN.value)) # <class 'int'>
print(EnumWeek.SUN.value == 0) # True
print(EnumWeek.SUN == EnumWeek2.SUN) # False
print(EnumWeek.SUN == EnumWeek.SUN) # True
print(EnumWeek.SUN is EnumWeek2.SUN) # False
print(EnumWeek.SUN is EnumWeek.SUN) # True

    使用枚举类注意事项如下所示:

from enum import Enum

class EnumWeek(Enum):
    SUN = 0
    MON=1
    TUE=2
    WED=3
    THU=4
    FRI=5
    SAT=0

print(EnumWeek.SAT) # EnumWeek.SUN
from enum import Enum,unique

@unique
class EnumWeek(Enum):
    SUN = 0
    MON=1
    TUE=2
    WED=3
    THU=4
    FRI=5
    SAT=0

    输出结果如下所示:

Traceback (most recent call last):
  File "C:\Users\admin\Documents\PyCharmProjects\MyPythonProjects\LearningCode\LearningEnum.py", line 4, in <module>
    class EnumWeek(Enum):
  File "D:\Program Files\Python\lib\enum.py", line 1013, in unique
    raise ValueError('duplicate values found in %r: %s' %
ValueError: duplicate values found in <enum 'EnumWeek'>: SAT -> SUN
from enum import Enum,unique,auto

@unique
class EnumWeek(Enum):
    SUN = auto()
    MON=auto()
    TUE=auto()
    WED=auto()
    THU=auto()
    FRI=auto()
    SAT=auto()

print(EnumWeek.SAT.value) # 7
print(EnumWeek.WED.value) # 4
from enum import Enum,unique,auto

@unique
class EnumWeek(Enum):
    SUN = auto()
    MON=auto()
    TUE=auto()
    WED=auto()
    THU=auto()
    FRI=auto()
    SAT=auto()

for week in EnumWeek:
    print(f"week is {week}:{week.value}")

    输出结果如下所示:

week is EnumWeek.SUN:1
week is EnumWeek.MON:2
week is EnumWeek.TUE:3
week is EnumWeek.WED:4
week is EnumWeek.THU:5
week is EnumWeek.FRI:6
week is EnumWeek.SAT:7
上一篇下一篇

猜你喜欢

热点阅读