In python I have:
class Animal(enum.Enum):
dog = 1
cat = 2
lion = 3
How can I do comparison between their numirical values? For example I want to do something like this:
if cat > dog:
# Something
CodePudding user response:
You can use .value attribute get the numerical value.
>>> import enum
>>>
>>> class Animal(enum.Enum):
... dog = 1
... cat = 2
... lion = 3
...
>>>
>>> Animal.dog.value
1
>>> Animal.cat.value
2
>>>
>>> Animal.cat.value > Animal.dog.value
True
Alternatively you can implement your own Enum class just like OrderedEnum(as @Yuri Ginsburg mentioned in the comment) with all magic methods required for comparison, thereby you can compare the variants directly.
>>> Animal.cat < Animal.dog
True
