[英]How can I have elements in an Enum evaluate as their value by default?
Is there anyway I can have an Enum like below无论如何我可以有一个像下面这样的枚举
class Key(Enum):
CUSTOMER_ID = 'c_id'
PHONE_NUMBER = 'phone'
such that calling Key.CUSTOMER_ID
evaluates to 'c_id'
by default, without the need of calling CUSTOMER_ID.value
?这样调用Key.CUSTOMER_ID
默认评估为'c_id'
,而不需要调用CUSTOMER_ID.value
?
Is there any method I can override that changes what the object returned when evaluated is?有什么方法我可以重写来改变评估时返回的 object 是什么?
When you want the Enum members to evaluate as their value, you need to mixin their value type:当您希望 Enum 成员评估为它们的值时,您需要混合它们的值类型:
class Key(str, Enum): # note that `str` is before `Enum`
CUSTOMER_ID = 'c_id'
PHONE_NUMBER = 'phone'
and in use:并在使用中:
>>> Key.PHONE_NUMBER == 'phone'
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.