Comparison of enumerations
Because enumeration members are not ordered, they only support comparison by identity and equality. Let's take a look at the use of == and is:
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- from enum import Enum class User(Enum): Twowater = 98 Liangdianshui = 30 Tom = 12 Twowater = User.Twowater Liangdianshui = User.Liangdianshui print(Twowater == Liangdianshui, Twowater == User.Twowater) print(Twowater is Liangdianshui, Twowater is User.Twowater) try: print('\n'.join(' ' + s.name for s in sorted(User))) except TypeError as err: print(' Error : {}'.format(err))
The output result:
False True False True Error : '<' not supported between instances of 'User' and 'User'
You can look at the final output result and report an exception. That is because of the greater than and less than comparison operations. operator raises a TypeError exception. That is to say, the enumeration of the Enum class does not support comparison of the size operator.
So can the enumeration class be used to compare sizes?
Of course it is possible. Using the IntEnum class for enumeration supports the comparison function.
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import enum class User(enum.IntEnum): Twowater = 98 Liangdianshui = 30 Tom = 12 try: print('\n'.join(s.name for s in sorted(User))) except TypeError as err: print(' Error : {}'.format(err))
Look at the output results:
Tom Liangdianshui Twowater
You can see from the output results that the members of the enumeration class are sorted by their value size. In other words, size comparisons can be made.