• Index

### 关于作者

#### 使用枚举类

JAN = 1
FEB = 2
MAR = 3
...
NOV = 11
DEC = 12


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开始计数。

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


### 练习

Studentgender属性改造为枚举类型，可以避免使用字符串：

# -*- coding: utf-8 -*-
from enum import Enum, 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)
if bart.gender == Gender.Male:
print('测试通过!')
else:
print('测试失败!')


### 小结

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

use_enum.py