Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Data Classes for Representation

00:00 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.

00:22 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.

00:45 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.

01:03 Let’s implement a user-friendly representation of a PlayingCard.

01:38 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 Deck.

02:43 Note, 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.

03:06 Now that you know how to alter the appearance of data classes, in the next section, you’ll see how to allow comparisons between instances of a data class.

Become a Member to join the conversation.