受 django 启发,让枚举类 label 返回中文

2023-07-19 18:28:03 +08:00
 wuwukai007
from enum import Enum

class XIntegerChoices(Enum):
    def __new__(cls, value, label):
        obj = object.__new__(cls)
        obj._value_ = value
        obj._label = label
        return obj

    def __eq__(self, other):
        if isinstance(other, int):
            return other == self.value
        if isinstance(other, XIntegerChoices):
            return other.value == self.value
        return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def __lt__(self, other):
        if isinstance(other, int):
            return self.value < other
        if isinstance(other, XIntegerChoices):
            return self.value < other.value
        raise TypeError

    def __le__(self, other):
        return self.__eq__(other) or self.__lt__(other)

    def __gt__(self, other):
        if isinstance(other, int):
            return self.value > other
        if isinstance(other, XIntegerChoices):
            return self.value > other.value
        raise TypeError

    def __ge__(self, other):
        return self.__eq__(other) or self.__gt__(other)

    def __hash__(self):
        return hash(self.value)

    @property
    def value(self):
        return self._value_

    @property
    def label(self):
        return self._label

    @classmethod
    def members(self):
        return list(self)


class Action(XIntegerChoices):
    CREATED = (1, "创建")


if __name__ == '__main__':

    print(Action.CREATED == 2)
    print(Action.CREATED.label)
    print(Action.members())

# False
# 创建
# [<Action.CREATED: 1>]
1220 次点击
所在节点    Python
4 条回复
joApioVVx4M4X6Rf
2023-07-20 08:21:56 +08:00
这个实现方式好棒!
bthulu
2023-07-20 13:36:46 +08:00
你就不能直接用中文枚举么? 用中文是会要了你的命, 还是丢了你的逼格?
print(Action.创建)
wuwukai007
2023-07-20 15:22:44 +08:00
@bthulu 如果是中英文+符号 混搭肯定不行,要考虑下代码健壮性,比如 应用商店(APP)
gujigujij
2023-07-24 14:26:53 +08:00
Enum 原生支持的

```

class CardTypeEnum(Enum):
ID_CARD = (1, '身份证')
TRAVEL_FOR_HK_MR = (2, '港澳居民来往内地通行证')
TRAVEL_FOR_TW = (3, '台湾居民来往大陆通行证')
PASSPORT = (4, '护照')

def __init__(self, code, text):
self.code = code
self.text = text


print(CardTypeEnum.ID_CARD.text )
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/958087

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX