Data Classes for Representation
Representation. Recall that we can easily create an entire deck of cards. While this representation of a
Deck is explicit and kind of readable, it’s also extremely verbose. As you can see here, the entire
Deck takes up most of the screen.
Let’s add a more concise representation. In general, a Python object has two different string representations: The repr of the object is defined by the
.__repr__() method and should return a developer-friendly representation of the object. If possible, this should be code that can recreate the object. Data classes do this.
The string representation is defined by the
.__str__() method and should return a user-friendly representation of the object. Data classes don’t implement the
.__str__() method by default, so Python falls back to the
.__repr__() method already seen.
The cards now look much nicer, but the deck is still as verbose as ever. To show that it’s possible to add your own
.__repr__() method as well, we will violate the principle that it should return code that can recreate an object. Practicality beats purity, after all. The following code adds a more concise representation of the
!s specifier in the format string. It means that we explicitly want to use the
str() string representation of each
PlayingCard. With the new
.__repr__(), the representation of the
Deck is easier on the eyes, as seen here.
Become a Member to join the conversation.