首页 > 其他分享 >枚举类

枚举类

时间:2023-01-12 20:46:07浏览次数:46  
标签:day1 枚举 Mon print Tue Weekday

枚举类

使用能够以调用属性的方式(类名.属性名)、调用元素的方式[](list[下标]、tuple[下标]、dict[key])、调用函数的方式(函数())来调用常量,方便常量的使用和管理

from enum import Enum

Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
Month是一个枚举类

@unique #装饰器检查元素是否有重合,有重复值会报错
class Weekday(Enum):
   Sun = 0 # Sun的value被设定为0
   Mon = 1
   Tue = 2
   Wed = 3
   Thu = 4
   Fri = 5
   Sat = 6

访问枚举类的元素方式很多

>>> day1 = Weekday.Mon  对象的属性调用
>>> print(day1)
Weekday.Mon
>>> print(Weekday.Tue)
Weekday.Tue
>>> print(Weekday['Tue'])   取元素
Weekday.Tue
>>> print(Weekday.Tue.value)    dict 的key 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

标签:day1,枚举,Mon,print,Tue,Weekday
From: https://www.cnblogs.com/HugoWang010220/p/17047870.html

相关文章