在使用Python的过程中,经常会需要用到映射关系,一般想到的是使用dict,比如
fruits_map = {
"apple": "red",
"banana": "yellow",
"watermelon": "green"
}
这时候,我们如果知道key,就能很快知道对应的value,但如果我们同时也想通过value,获取key呢,这时候用dict就显得不太合适了,需要遍历其中的key,判断其value是否和想要的相等,或者需要再写了一个dict。
对于这种情况,其实使用枚举类就可以较好的解决问题
from enum import Enum, unique
@unique
class Fruits(Enum):
apple = "red"
banana = "yellow"
watermelon = "green"
print(Fruits.apple.name). # apple
print(Fruits.app.value) # red
print(Fruits(red).name). # apple
如果这时又需要其他的属性,跟这些key相关,可以使用@property定义新的函数,其返回值为想要的值,并且可以在该函数中进行相关的处理
from enum import Enum, unique
@unique
class Fruits(Enum):
apple = "red"
banana = "yellow"
watermelon = "green"
strawberry = "red"
@property
def size(self):
if self.name in ["apple", "watermelon"]:
return "big"
else:
return "small"
@property
def price(self):
return fruits_map[self.name]
fruits_map = {
"apple" : 10,
"banana": 11,
"watermelon": 12,
"strawberry": 13
}
print(Fruits("yellow").size) # small
print(Fruits("yellow").price) # 11
但是对于一些属性,value的类型不确定,有可能是int,也有可能是string,对于这些情况,我们可以写一个CommonEnum来处理
from enum import Enum, unique
class CommonEnum(Enum):
def __new__(cls, *values):
obj = object.__new__(cls)
# first value is canonical value
obj._value_ = values[0]
for other_value in values[1:]:
cls._value2member_map_[other_value] = obj
obj._all_values = values
return obj
@unique
class FruitType(CommonEnum):
"""
代码位对应的映射关系
"""
apple = 1, "1"
banner = 2, "2"
orange = 3, "3"
watermelon = 4, "4"
strawberry = 5, "5"
print(FruitType(1).name) # apple
print(FruitType("1").name) # apple
这样就可以兼容value是Int和string的情况。