python 枚举类

在使用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的情况。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值