Python枚举类

Posted 听着music睡

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python枚举类相关的知识,希望对你有一定的参考价值。

Enum可以把一组相关常量定义在一个class中,且class不可变,而且成员可以直接比较。

 

定义枚举类:

 

from enum import Enum, unique

@unique
class Weekday(Enum):
    Sun = 0 # Sun的value被设定为0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6

可以看到括号里面是Enum ,即继承自枚举类

然后给这个枚举类的每个成员赋予一个值

@unique装饰器可以帮助我们检查保证没有重复值。

 

使用:

>>> 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(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

  

 

以上是关于Python枚举类的主要内容,如果未能解决你的问题,请参考以下文章

Python-枚举

Java 枚举类的基本使用

Python类OOPs概念[重复]

同名的类函数宏和枚举器

带有红宝石集合/可枚举的酷技巧和富有表现力的片段[关闭]

Python枚举类