要封装我正在使用的状态列表 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
)?
原文由 sophros 发布,翻译遵循 CC BY-SA 4.0 许可协议
似乎从
str
类同时继承Enum
就足够了:棘手的部分是继承链中类 的顺序 _很重要_,如下所示:
投掷:
使用正确的类,可以对
MyEnum
执行以下操作:作为旁注,似乎 格式化字符串 不需要特殊的继承技巧,它甚至适用于
Enum
仅继承: