Python中的枚举类

时间:2015-08-03 07:02:14

标签: python enums getstring

我想在python中创建一个Enum类。我还需要一些get_str()方法,例如:

class Operation (object):
    START = 0
    STOP = 1
    (...)

    def get_str(self):
        operation_dispatcher = {
             Operation.START: "start", 
             Operation.STOP: "stop",
             (...)

             }
    return operation_dispatcher[self]

但不幸的是,这种方法并不奏效。对象是整数,我收到错误消息' int'对象没有属性' get_str' ...您是否知道如何实现该功能?

我尝试过这样的事情:

Operation.get_str(operation_reference)以及 operation_reference.get_str()

更新:

class EnumMeta(type):
    def __getattribute__(self, name):
        return self(super(EnumMeta, self).__getattribute__(name))

class Enum(object):
    __metaclass__ = EnumMeta

    def __init__(self, value):
        super(Enum, self).__init__()

        self.value = value[0]
        self.repr = value[1]

    def __eq__(self, other):
        if isinstance(other, Enum):
            return self.value == other.value
        elif isinstance(other, int):
            return self.value == other
        else:
            return object.__eq__(Enum, other)

    def __repr__(self):
        return str(self.repr)

class Operation(Enum):
    START = (0, "start")
    STOP = (1, "stop")
    (...)

operation_dispatcher = {
             Operation.START: start_method, 
             Operation.STOP: stop_method,
             (...) }

# invoking
operation_dispatcher[Operation.START.value]()

2 个答案:

答案 0 :(得分:0)

我建议使用元类来实现目标,以便最小化客户端代码。所以首先要检查下面的元类:

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__并使用attributes值作为构造函数参数返回子类的实例。它还更新原始值,以便不每次都创建一个新实例,并使用对象的引用进行相等性检查

然后定义一个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"

答案 1 :(得分:0)

Python中的

foo()是:

  • 内置自Python 3.4
  • 可用作Python 3.3的backport到Python 2.4
  • enhanced library中提供,其中还包含基于课程的EnumNamedTuple课程

使用您的代码看起来像:

Constant