Enum class in python -
this question has answer here:
- how can represent 'enum' in python? 43 answers
i create enum class in python. need get_str() method, 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 approach doesn't work. objects ints , got error message 'int' object has no attribute 'get_str'... have idea how implement functionality?
i tried like:
operation.get_str(operation_reference) 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]()
i recommend achieve goal using metaclasses, in order minimise client code. first of checkout below metaclass:
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
it overrides __getattribute__
, returns instance of child class using attributes value constructor argument. updates original value, in order not create new instance every time, , besides make equality check using reference of object
then define enum
class this:
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)
this base class implements equals (==
) operator, compare using int value, , __repr__
method, return string representation of enum. here go:
class operation(enum): start = (0, "start") stop = (1, "stop") >>> operation.start == operation.start true >>> operation.start operation.start true >>> operation.start == operation.stop false >>> operation.start "start" >>> repr(operation.stop) "stop"
Comments
Post a Comment