8.6 Creating a class that has orderable objects
We often need objects that can be sorted into order. Log records, to give one example, are often ordered by date and time. Most of our class definitions have not included the features necessary for sorting objects into order. Many of the recipes have kept objects in mappings or sets based on the internal hash value computed by the __hash__() method, and an equality test defined by the __eq__() method.
In order to keep items in a sorted collection, we’ll need the comparison methods that implement <, >, <=, and >=. These comparisons are all based on the attribute values of each object.
When we extend the NamedTuple class, the comparison methods that apply to the tuple class are available. If we defined class using the @dataclass decorator, the comparison methods are not provided by default. We can use @dataclass(order=True) to have the ordering methods included. For this recipe, we’ll look...