gpt4 book ai didi

python - Python 中基于字符串的枚举

转载 作者:行者123 更新时间:2023-11-28 21:31:14 25 4
gpt4 key购买 nike

为了封装状态列表,我正在使用 enum 模块:

from enum import Enum

class MyEnum(Enum):
state1='state1'
state2 = 'state2'

state = MyEnum.state1
MyEnum['state1'] == state # here it works
'state1' == state # here it does not throw but returns False (fail!)

但是,问题是我需要在脚本的许多上下文中将这些值无缝地用作字符串,例如:

select_query1 = select(...).where(Process.status == str(MyEnum.state1))  # works but ugly

select_query2 = select(...).where(Process.status == MyEnum.state1) # throws exeption

如何避免调用额外的类型转换(上面的str(state))或基础值(state.value)?

最佳答案

看来和Enum同时继承str类就够了:

from enum import Enum

class MyEnum(str, Enum):
state1 = 'state1'
state2 = 'state2'

棘手的部分是继承链中类的顺序很重要,如下所示:

class MyEnum(Enum, str):
state1 = 'state1'
state2 = 'state2'

抛出:

TypeError: new enumerations should be created as `EnumName([mixin_type, ...] [data_type,] enum_type)`

使用正确的类可以在 MyEnum 上进行以下操作:

print('This is the state value: ' + state)

附带说明一下,formatted strings 似乎不需要特殊的继承技巧。甚至只对 Enum 继承有效:

msg = f'This is the state value: {state}'  # works without inheriting from str

关于python - Python 中基于字符串的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58608361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com