Python中的枚举类

这个问题在这里已经有了答案:

  • 我如何在Python中表示'Enum'? 43个答案

  • 我会建议使用元类实现您的目标,以最大限度地减少客户端代码。 所以首先检查下面的元类:

    class EnumMeta(type):
        def __getattribute__(self, name):
            actual_value = super(EnumMeta, self).__getattribute__(name)
            if isinstance(actual_value, self):
                return actual_value
            else:
                new_value = self(actual_value)
                super(EnumMeta, self).__setattr__(name, new_value)
                return new_value
    

    它只是覆盖__getattribute__并使用属性值作为构造函数参数返回子类的实例。 此外,它还更新原始值,以便不会每次创建新实例,并且还要使用对象的引用进行相等性检查

    然后像这样定义一个Enum类:

    class Enum(object):
        __metaclass__ = EnumMeta
    
        def __init__(self, value):
            super(Enum, self).__init__()
    
            self.value = value[0]
            self.repr = value[1]
    
        def __repr__(self):
            return str(self.repr)
    

    此基类实现equals( == )运算符,以使用int值和__repr__方法进行比较以返回枚举的字符串表示形式。 所以你去了:

    class Operation(Enum):
        START = (0, "start")
        STOP = (1, "stop")
    
    >>> Operation.START == Operation.START
    True
    >>> Operation.START is Operation.START
    True
    >>> Operation.START == Operation.STOP
    False
    >>> Operation.START
    "start"
    >>> repr(Operation.STOP)
    "stop"
    

    Python中的Enum是:

  • 内置于Python 3.4中
  • 可用作Python 3.3到Python 2.4的后端
  • 可用于增强库中,该库还包含基于类的NamedTupleConstant
  • 使用你的代码如下所示:

    from aenum import IntEnum   # or from enum import IntEnum
    
    class Operation(IntEnum):
        START = 0
        STOP = 1
    
    >>> Operation.START
    <Operation.START: 0>
    
    >>> Operation['START']
    <Operation.START: 0>
    
    >>> Operation(0)
    <Operation.START: 0>
    
    >>> Operation.STOP is Operation.STOP
    True
    
    >>> list(Operation)
    [<Operation.START: 0>, <Operation.STOP: 1>]
    
    >>> Operation.STOP.name
    'STOP'
    
    >>> Operation.STOP.value
    1
    
    链接地址: http://www.djcxy.com/p/91739.html

    上一篇: Enum class in python

    下一篇: What's the cleanest way to set up an enumeration in Python?