python 如何用枚举处理数据状态?

假设我有一个状态字段,有三种含义,分别为:编号,别名,说明

如:

id alias title
0 wait 待审核
1 yes 已通过
2 no 未通过

我们平时都是这么定义的:

class State(Enum):
    wait = 0
    yes = 1
    no = 2

有没有一种方法,可以定义多关联的状态,相互对应关系。
我希望可以:
wait 找到 待审核 和 0
0 找到 wait 和 待审核
待审核 找到 0 和 wait

同时为了前端展示,可能需要:

[
  {id: 0, title: 待审核},
  {id: 1, title: 已通过},
  {id: 2, title: 未通过}
]

如何有已经开源的库,请推荐一下

阅读 2k
1 个回答

试试通过id/alias/title来比较

class State:
    __slots__ =("id","alias","title")
    def __init__(self,id:int = None,alias:str =  None,title:str = None):
        self.id = id
        self.alias = alias
        self.title = title
        pass

    def __eq__(self, other):
        if other is None: return False
        otype = type(other)
        if otype is int: return self.id == other
        if otype is str: return self.alias == self.alias \
                                or self.title == self.title

        if otype is State: return self == other.id \
                                  or self == other.alias \
                                  or self == other.title
        return False
#-------------------------
x  = State(0,"wait","等待")
print(x == 0)
print(x == "wait")
print(x == State(title= "等待"))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题