我想在 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]()