简体   繁体   English

默认情况下,如何让 Enum 中的元素评估为它们的值?

[英]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.

相关问题 如何为记录类数据对象的枚举属性设置默认值? - How can I set a default value for an enum attribute of a recordclass dataobject? 如何在列表中找到Python中具有相同值的元素? - How can I find elements in a list that have same value in Python? 默认情况下,我如何在 Atom 中有一个 venv? - How can I have a venv in Atom by default? 如何用该字典的键替换列向量中等于我拥有的字典的值的元素 - How can I replace elements in a column vector that equal the value of a dictionary I have with the keys of that dictionary 当传递给模块中的函数时,如何设置变量作用域的默认值? - How can I have / effect a default value for variable scoping when passed to a function in a module? 如何在 python 中为用户输入的光标位置设置默认值? - How can i have a default value in cursor place for the user input in python? 如何避免在Storm中出现“警告:字段'xxx'没有默认值”? - How can I avoid “Warning: Field 'xxx' doesn't have a default value” in Storm? 如何键入使用默认值动态创建的枚举? - How to type Enum created dynamically with a default value? 我有一个表达式的操作数和操作存储在单独的变量中,我该如何评估? - I have the operands and operation of an expression stored in separate variables, how can I evaluate? 我可以将字典用作具有默认返回值的属性吗? - can I have a dictionary act as an attribute with a default return value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM