在Python中的基于字符串的枚举
- 论坛
- 在Python中的基于字符串的枚举
30 浏览
在Python中的基于字符串的枚举
为了封装一个状态列表,我使用了enum
模块:
from enum import Enum class MyEnum(Enum): state1='state1' state2 = 'state2' state = MyEnum.state1 MyEnum['state1'] == state # 这里可以正常工作 'state1' == state # 这里不会报错,但返回False(失败!)
然而,问题是我需要在脚本的许多上下文中无缝使用这些值作为字符串,比如:
select_query1 = select(...).where(Process.status == str(MyEnum.state1)) # 可以工作,但不够简洁 select_query2 = select(...).where(Process.status == MyEnum.state1) # 报错
如何在不调用额外的类型转换(str(state)
)或底层值(state.value
)的情况下解决这个问题?