python 的枚举

enum枚举是常用的功能

from enum import Enum

shapes = Enum('shape', ('Line', 'Points', 'Polyline', 'Polygon', 'Rectangle', 'Rounded Rectangle', 'Ellipse',
                             'Arc', 'Chord', 'Pie', 'Path', 'Text', 'Pixmap'))
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
print(shapes._member_map_)  #__dict__
#OrderedDict([('Line', <shape.Line: 1>), ('Points', <shape.Points: 2>), ('Polyline', <shape.Polyline: 3>), ('Polygon', <shape.Polygon: 4>), ('Rectangle', <shape.Rectangle: 5>), ('Rounded Rectangle', <shape.Rounded Rectangle: 6>), ('Ellipse', <shape.Ellipse: 7>), ('Arc', <shape.Arc: 8>), ('Chord', <shape.Chord: 9>), ('Pie', <shape.Pie: 10>), ('Path', <shape.Path: 11>), ('Text', <shape.Text: 12>), ('Pixmap', <shape.Pixmap: 13>)])
shape = shapes['Pie']
print(shape)
print('%s: name %s ,num is %s '%(shapes['Pie'], shapes['Pie'].name, shapes['Pie'].value ))
shape = shapes(3)
print(Month._member_map_.__len__())

class WEEKDAY(Enum):
    Sun = 7 # Sun的value被设定为0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6

for p,d in WEEKDAY.__members__.items():
    print(p)
    print(p, ':', d.name, ',', d.value,'(', d, ')')
print(WEEKDAY['Sun'])
print(WEEKDAY.__len__())

1.      首先,定义枚举要导入enum模块。

2.      枚举定义继承Enum类,定义类用class关键字,。

注意:

  定义枚举时,成员名称不允许重复

  默认情况下,不同的成员值允许相同。但是两个相同值的成员,第二个成员的名称被视作第一个成员的别名 

   如果枚举中存在相同值的成员,在通过值获取枚举成员时,只能获取到第一个成员

 如果要限制定义枚举时,不能定义相同值的成员。可以使用装饰器@unique【要导入unique模块】

 

每一个成员可以用shapes(3)或shapes[‘Pie’]来访问,分别具有属性name和value,合起来构成dict: _member_map_

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值