python3 enum模块的应用实例详解
一、枚举与字典类型
字典类型的缺点:
1.值可变
2.没有防止相同标签的功能
枚举的特点:
1.枚举类的值不可以被外界更改
2.不能存在相同的标签,但允许不同标签存在相同的枚举值,即后者相当于前者的别名
3.枚举值可以是任意类型
4.枚举标签尽量用大写
from enum import Enum #普通类 class dict(): green = 1 green = 2 red = 3 dict.red = 4 print(dict.red) >>> 4 class VIP(Enum): RED = 1 GREEN =2 YELLOW = 3 VIP.GREEN = 5 #枚举值不能动态更改 >>>File "D:\python\lib\enum.py", line 361, in __setattr__ raise AttributeError('Cannot reassign members.') AttributeError: Cannot reassign members. class VIP(Enum): RED = 1 GREEN =2 YELLOW = 3 YELLOW = 3 #不能出现相同的标签 >>>File "D:\python\lib\enum.py", line 92, in __setitem__ raise TypeError('Attempted to reuse key: %r' % key) TypeError: Attempted to reuse key: 'YELLOW' class VIP(Enum): RED = 1 GREEN =2 YELLOW = 3 BLUE = 3 print(VIP.BLUE) >>>VIP.YELLOW #即VIP.BLUE类似于VIP.YELLOW的别名 class VIP(Enum): RED = 1 #整型 BLUE = 1.2 #浮点型 GREEN = 'green' #str YELLOW = True #布尔值
二、枚举类型、枚举名称、枚举值
1.获取枚举类型中的标签:.name属性
2.获取枚举类型中的值:.value属性
from enum import Enum class VIP(Enum): RED = 1 GREEN = 'green' YELLOW = True BLUE = 1.2 print(VIP.RED) #枚举的类型 print(VIP.YELLOW.name) #枚举的标签 print(VIP.YELLOW.value) #枚举的数值 print('遍历成员。。。') for i in VIP.__members__.items(): #枚举的遍历 print(i) >>> VIP.RED RED 1 遍历成员。。。 ('RED', <VIP.RED: 1>) ('GREEN', <VIP.GREEN: 'green'>) ('YELLOW', <VIP.RED: 1>) ('BLUE', <VIP.BLUE: 1.2>)
三、枚举的比较运算
class VIP(Enum): RED = 1 GREEN = 'green' YELLOW = True BLUE = 2 #枚举的比较 a = VIP.RED == VIP.RED #枚举值可以做等值比较 b = VIP.RED == VIP.GREEN c = VIP.RED is VIP.RED d = VIP.RED == 1 #枚举标签与枚举值比较,并不相等 f = VIP.RED < VIP.BLUE #枚举值不支持大小比较,打印会报错TypeError: '<' not supported between instances of 'VIP' and 'VIP' print(a) print(b) print(c) print(d) >>> True False True False
四、枚举的转换
class VIP(Enum): RED = 1 GREEN = 'green' YELLOW = True BLUE = 2 print(VIP(2)) #通过具体值获取枚举类型,返回VIP.BLUE print(VIP('green')) #返回VIP.GREEN
五、枚举的拓展unique
unique:规定两个不同的枚举不能取相同的值
from enum import Enum,unique @unique class VIP(Enum): RED = 1 GREEN = 1 YELLOW = True BLUE = 2 >>>报错 ValueError: duplicate values found in <enum 'VIP'>: GREEN -> RED, YELLOW -> RED
六、枚举的拓展auto
如果我们对枚举值没有特别的要求或者没有太大的影响时,我们可以使用auto自动生成对应的数值
from enum import Enum,auto class VIP(Enum): RED = auto() GREEN = auto() YELLOW = auto() BLUE = auto() for i in VIP.__members__.items(): #遍历枚举 print(i) >>> ('RED', <VIP.RED: 1>) ('GREEN', <VIP.GREEN: 2>) ('YELLOW', <VIP.YELLOW: 3>) ('BLUE', <VIP.BLUE: 4>)
其实,auto值是调用_generate_next_value_()
函数来产生的,我们可以通过重写该函数
from enum import Enum,auto class auto_test(Enum): def _generate_next_value_(name, start, count, last_values): return name class VIP(auto_test): RED = auto() GREEN = auto() YELLOW = auto() BLUE = auto() # for i in VIP.__members__.items(): #遍历枚举 # print(i) print(list(VIP)) #转换列表 >>> [<VIP.RED: 'RED'>, <VIP.GREEN: 'GREEN'>, <VIP.YELLOW: 'YELLOW'>, <VIP.BLUE: 'BLUE'>]
总结
以上所述是小编给大家介绍的python3 enum模块的应用实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
赞 (0)