Python学习札记(三十九) 面向对象编程 Object Oriented Program 10
参考:使用枚举类
NOTE
#!/usr/bin/env python3
from enum import Enum
def main():
Mouth = Enum('Mouth', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
for name, attr in Mouth.__members__.items():
print(name, '=>', attr, '=>', attr.value)
if __name__ == '__main__':
main()
sh-3.2# ./oop11.py
Jan => Mouth.Jan => 1
Feb => Mouth.Feb => 2
Mar => Mouth.Mar => 3
Apr => Mouth.Apr => 4
May => Mouth.May => 5
Jun => Mouth.Jun => 6
Jul => Mouth.Jul => 7
Aug => Mouth.Aug => 8
Sep => Mouth.Sep => 9
Oct => Mouth.Oct => 10
Nov => Mouth.Nov => 11
Dec => Mouth.Dec => 12
1.当我们定义常量的时候,一般使用大写的字母来表示,但是本质上还是需要修改的。
更好的方法是为这样的枚举类型定义一个class类型,然后,每个常量都是class的一个唯一实例。Python提供了Enum类来实现这个功能。
枚举类Mouth有12个成员,每个成员默认有value属性,value属性默认从1开始分配。
2.也可以通过类的继承更好的控制枚举类:
from enum import Enum, unique
@unique
class Week(Enum):
"""docstring for Week"""
Sun = 0
Mon = 1
Tue = 2
Thu = 3
Wed = 4
Fri = 5
Sat = 6
print(Week.Sun)
print(Week['Tue'])
print(Week.Fri.value)
Week.Sun
Week.Tue
5
a.用成员名称引用枚举常量
b.根据value的值获得枚举常量
2017/3/7
To improve is to change, to be perfect is to change often.