python教程

当前位置:首页 > python面向对象 > 当前文章

python面向对象

python枚举项比较运算及相同的key和value的处理

2021-11-09 188赞 老董笔记

  python的枚举类各个枚举项之间可以用==或者 is来进行等值比较,但是不能进行大小比较。如果枚举项出现相同的key就会报错,如果值相同则不会报错,后面的枚举项会作为第一个的别名。

  1、枚举项==或者 is来等值比较

# -*- coding: utf-8 -*-

from enum import Enum

class Weekday(Enum):
  Mon = 1
  Tue = 2
  Wed = 3
  Thu = 4
  Fri = 5
  Sat = 6
  Sun = 7
  Dong = 1 # 自己随便加了1个


print(Weekday['Mon'] == Weekday['Tue'])
print(Weekday.Mon == Weekday.Tue)
print('----------------------------')
print(Weekday['Mon'] is Weekday['Dong'])
print(Weekday.Mon is Weekday.Dong)
False
False
----------------------------
True
True

  2、枚举项中的 key 不能相同,value 可以相同

# -*- coding: utf-8 -*-
from enum import Enum

class Weekday(Enum):
  Mon = 1
  Tue = 2
  Wed = 3
  Thu = 4
  Fri = 5
  Sat = 6
  Sun = 7
  Mon = 1 # 重复
TypeError: Attempted to reuse key: 'Mon'

# -*- coding: utf-8 -*-
from enum import Enum

class Weekday(Enum):
  Mon = 1
  Tue = 2
  Wed = 3
  Thu = 4
  Fri = 5
  Sat = 6
  Sun = 7
  Sun2 = 7 # 值相同
  Sun3 = 7 # 值相同


print(Weekday.Sun2) # 结果是Weekday.Sun
print(Weekday.Sun3) # Weekday.Sun
Weekday.Sun
Weekday.Sun

  如果需要枚举项中的value不能相同,可以用@unique 装饰器来修饰,这样当枚举类各项出现相同值时会报 name 'unique' is not defined 错。

# -*- coding: utf-8 -*-
from enum import Enum

@unique 
class Weekday(Enum):
  Mon = 1
  Tue = 2
  Wed = 3
  Thu = 4
  Fri = 5
  Sat = 6
  Sun = 7
  Sun2 = 7 # 值相同
NameError: name 'unique' is not defined

感兴趣直接点击图片获取>>

文章评论

python枚举项比较运算及相同的key和value的处理文章写得不错,值得赞赏