
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>] 1 joApioVVx4M4X6Rf 2023-07-20 08:21:56 +08:00 这个实现方式好棒! |
2 bthulu 2023-07-20 13:36:46 +08:00 你就不能直接用中文枚举么? 用中文是会要了你的命, 还是丢了你的逼格? print(Action.创建) |
3 wuwukai007 OP @bthulu 如果是中英文+符号 混搭肯定不行,要考虑下代码健壮性,比如 应用商店(APP) |
4 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 ) ``` |