枚举类
当需要定义常量时, 通过大写变量名值用整数来定义,例如月份:
JAN = 1
FEB = 2
MAR = 3
...
NOV = 11
DEC = 12
这样的好处是简单,缺点任然是变量切类型是int
更好的方法是未这样的枚举类型定义一个class类,然后每个常量时其中一个唯一实例,python提供了Enum
类来实现该功能
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
'Nov', 'Dec'))
# 这样就获得了Month类型的枚举类,可以直接使用Month.Jan来引用一个常量,或者枚举它的所有成员:
# value属性则是自动赋给成员的int常量,默认从1开始计数。
for name, member in Month.__members__.items():
print(name, '=>', member, ',', member.value)
Jan => Month.Jan , 1
Feb => Month.Feb , 2
Mar => Month.Mar , 3
Apr => Month.Apr , 4
May => Month.May , 5
Jun => Month.Jun , 6
Jul => Month.Jul , 7
Aug => Month.Aug , 8
Sep => Month.Sep , 9
Oct => Month.Oct , 10
Nov => Month.Nov , 11
Dec => Month.Dec , 12
为了更精确的控制枚举类型,可以从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
# 各种用法
day1 = Weekday.Mon
print(day1)
print(Weekday.Tue)
print(Weekday['Tue'])
print(Weekday.Thu.value)
print(day1 == Weekday.Mon)
print(day1 == Weekday.Tue)
print(Weekday(1))
print(day1 == Weekday.Mon)
# ValueError: 7 is not a valid Weekday
# Weekday(7)
for name, member in Weekday.__members__.items():
print(name, '=>', member)
Weekday.Mon
Weekday.Tue
Weekday.Tue
4
True
False
Weekday.Mon
True
Sun => Weekday.Sun
Mon => Weekday.Mon
Tue => Weekday.Tue
Wed => Weekday.Wed
Thu => Weekday.Thu
Fri => Weekday.Fri
Sat => Weekday.Sat
练习
把Student
的gender
属性改造为枚举类型,可以避免使用字符串:
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("测试失败!")
测试通过!
posted on
2018-10-31 14:09 想喝猪肝汤 阅读(
...) 评论(
...) 编辑 收藏