Data Classes for Comparison
Comparison. In many card games, cards are compared to each other. For instance, in a typical trick taking game, the highest card takes the trick. As it is currently implemented, the
PlayingCard class does not support this kind of comparison.
This is, however, seemingly easy to rectify. The
@dataclass decorator has two forms. So far, you’ve used this simple form where
@dataclass is specified without any parentheses or parameters. However, you can also give parameters to the decorator in parentheses.
order to be
True, instances of
PlayingCard can be compared. How are the two cards compared, though? You’ve not specified how the ordering should be done, and for some reason Python seems to believe that a queen is higher than an ace.
PlayingCard to use this sort index for comparisons, we need to add a field
.sort_index to the class. However, this field should be calculated from the other fields
.sort_index is added as the first field of the class. This way, the comparison is first done using
.sort_index, and only if there are ties are any of the other fields used. Using
field(), you must also specify that
.sort_index should not be included as a parameter in the
.__init__() method, because it’s calculated from the
To avoid confusing the user about this implementation detail, it’s probably also a good idea to remove
.sort_index from the
repr of the class, as has been done in the code you’ve just seen. Finally, aces are high.
05:39 You can now easily create a sorted deck. And if you don’t care about sorting, this is how you draw a random hand of ten cards. In the next section of the course, you’ll take a look at how to make data classes immutable.
Become a Member to join the conversation.