Using dataclasses for mutable objects
There are two cases for any kind of class design:
- Is it stateless (immutable)? Does it embody attributes with values that never change? If so, see the Using typing.NamedTuple for immutable objects recipe for a way to build class definitions for stateless objects.
- Is it stateful (mutable)? Will there be state changes for one or more attributes? In this case, we can either build a class from the ground up, or we can leverage the
@dataclass
decorator to create a class definition from a few attributes and type hints.
Getting ready
We'll look closely at a stateful object that holds a hand of cards. Cards can be inserted into a hand and removed from a hand. In a game like Cribbage, the hand has a number of state changes. Initially, six cards are dealt to both players. The players will each place a pair of cards in a special pile, called the crib. The remaining four cards are played alternately to create scoring...