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

查看 46|回复 0
作者: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 __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
# 创建
# []
您需要登录后才可以回帖 登录 | 立即注册

返回顶部