默认情况下,如何在枚举中将元素评估为它们的值? [英] How can I have elements in an Enum evaluate as their value by default?

查看:82
本文介绍了默认情况下,如何在枚举中将元素评估为它们的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反正我可以有一个如下所示的枚举

Is there anyway I can have an Enum like below

class Key(Enum):
    CUSTOMER_ID = 'c_id'
    PHONE_NUMBER = 'phone'

从而调用 Key.CUSTOMER_ID 默认情况下计算为'c_id',而无需调用 CUSTOMER_ID.value

such that calling Key.CUSTOMER_ID evaluates to 'c_id' by default, without the need of calling CUSTOMER_ID.value?

有没有我可以重写的方法来更改评估时返回的对象是什么?

Is there any method I can override that changes what the object returned when evaluated is?

推荐答案

何时要枚举成员以评估其值,您需要混合其值类型:

When you want the Enum members to evaluate as their value, you need to mixin their value type:

class Key(str, Enum):             # note that `str` is before `Enum`
    CUSTOMER_ID = 'c_id'
    PHONE_NUMBER = 'phone'

使用中:

>>> Key.PHONE_NUMBER == 'phone'
True

这篇关于默认情况下,如何在枚举中将元素评估为它们的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆