Locked learning resources

You must own this product to watch this lesson.

Locked learning resources

You must own this product to watch this lesson.

Data Classes for Representation

This lesson is part of a Real Python video course by Darren Jones.

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.

You must own this product to join the conversation.