I would like to create an Enum class in python. I need also some get_str() method, something like:
class Operation (object):
START = 0
STOP = 1
(...)
def get_str(self):
operation_dispatcher = {
Operation.START: "start",
Operation.STOP: "stop",
(...)
}
return operation_dispatcher[self]
But unfortunately that approach doesn't work. The objects are ints and I got error message that 'int' object has no attribute 'get_str'... Do you have any idea how to implement that functionality?
I tried to do something like:
Operation.get_str(operation_reference) as well as operation_reference.get_str()
UPDATE:
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]()