Python3 枚举类
枚举(Enum)跟整型一样,是一种数据类型。它是一系列常量的集合,通常用于表示某些特定的有限集合,如月份、星期、状态、性别(男、女、不男不女)等,当一个变量有几种可能取值的时候,定义为枚举类型。
枚举是不可变类型,一旦定义创建,其成员的值不可改变,名称不可重复
枚举成员的值支持多种数据类型,如字符串、布尔或整型等,如要指定为整型,可继承IntEnum类。
枚举成员不可以比较大小,但可以通过is、is not 和==、!=进行同性或等值比较。
实例代码:
from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
for name, member in Month.__members__.items():
print(name, '=>', member, ',', member.value)
value
属性则是自动赋给成员的int
常量,默认从1
开始计数。
如果需要更精确地控制枚举类型,可以从Enum
派生出自定义类:
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
@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
可见,既可以用成员名称引用枚举常量,又可以直接根据value的值获得枚举常量。
练习
把Student的gender属性改为枚举类型,可以避免使用字符串
from enum import Enum, unique
@unique
class Gender(Enum): Male=0 Female=1 class Student(object): def __init__(self, name, gender): self.name = name self.gender = gender bart=Student('Bart',Gender.Male)
https://segmentfault.com/a/1190000017327003
参考自廖老师的python3.