Enum class in python
This question already has an answer here:
I would recommend to achieve you goal using metaclasses, in order to minimise the client code. So first of all checkout the 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 simply overrides the __getattribute__
and returns an instance of the child class using the attributes value as the constructor argument. Also it updates the original value, in order not to create a new instance every time, and besides to make equality check using the reference of the object
Then define an Enum
class like 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, to compare using the int value, and __repr__
method, to return the string representation of your enum. So here you go:
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"
Enum
s in Python are either:
NamedTuple
and a Constant
class Using that your code would look like:
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/91740.html
上一篇: 使用函数属性作为返回值
下一篇: Python中的枚举类