In [1]:
WEEKDAY = {
'MON': 1,
'TUS': 2,
'WEN': 3,
'THU': 4,
'FRI': 5
}
class Color:
RED = 0
GREEN = 1
BLUE = 2
上面两种方法可以看做是简单的枚举类型的实现,如果只在局部范围内用到了这样的枚举变量是没有问题的,但问题在于它们都是可变的(mutable),也就是说可以在其它地方被修改从而影响其正常使用:
In [2]:
WEEKDAY['MON'] = WEEKDAY['FRI']
print(WEEKDAY)
通过类定义的枚举甚至可以实例化,变得不伦不类:
In [3]:
c = Color()
print(c.RED)
Color.RED = 2
print(c.RED)
当然也可以使用不可变类型(immutable),例如元组,但是这样就失去了枚举类型的本意,将标签退化为无意义的变量:
In [4]:
COLOR = ('R', 'G', 'B')
print(COLOR[0], COLOR[1], COLOR[2])
In [5]:
from enum import Enum, IntEnum, unique
try:
@unique
class WEEKDAY(Enum):
MON = 1
TUS = 2
WEN = 3
THU = 4
FRI = 1
except ValueError as e:
print(e)
In [6]:
try:
class Color(IntEnum):
RED = 0
GREEN = 1
BLUE = 'b'
except ValueError as e:
print(e)
更有趣的是 Enum
的成员均为单例(Singleton),并且不可实例化,不可更改:
In [7]:
class Color(Enum):
R = 0
G = 1
B = 2
In [8]:
try:
Color.R = 2
except AttributeError as e:
print(e)
虽然不可实例化,但可以将枚举成员赋值给变量:
In [9]:
red = Color(0)
green = Color(1)
blue = Color(2)
print(red, green, blue)
也可以进行比较判断:
In [10]:
print(red is Color.R)
print(red == Color.R)
print(red is blue)
print(green != Color.B)
print(red == 0) # 不等于任何非本枚举类的值
最后一点,由于枚举成员本身也是枚举类型,因此也可以通过枚举成员找到其它成员:
In [11]:
print(red.B)
print(red.B.G.R)
但是要谨慎使用这一特性,因为可能与成员原有的命名空间中的名称相冲突:
In [12]:
print(red.name, ':', red.value)
class Attr(Enum):
name = 'NAME'
value = 'VALUE'
print(Attr.name.value, Attr.value.name)