Locked learning resources

You must own this product to watch this lesson.

Locked learning resources

You must own this product to watch this lesson.

Comparison to Standard Classes

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

00:00 Comparison to standard classes. The code in this course is run using Python 3.9, but any version from 3.7 onwards should run it. The code is seen running with the bpython REPL, which offers an enhanced way to work directly with Python code, offering color coding and command completion.

00:22 Data classes are created using the @dataclass decorator, as seen onscreen. A data class comes with basic functionality already implemented.

00:47 For instance, you can instantiate, print, and compare data class instances straight out of the box.

01:08 Compare that to a regular class. A minimal regular class would look something like this. While this isn’t much more code to write, you can already see signs of the boilerplate pain: rank and suit are both repeated three times simply to initialize an object. Furthermore, if you try to use this plain class, you’ll notice that the representation of the objects is not very descriptive, and for some reason a queen of hearts is not the same as a queen of hearts.

02:11 Looking at this behavior, it seems as if data classes are helping us out behind the scenes. By default, data classes implement a .__repr__() method to provide a nice string representation and an .__eq__() method that can do basic object comparisons.

02:29 For the RegularCard class to imitate the data class version, you need to add these methods as well.

03:27 As you can see, this means extra work needs to be done to allow regular classes to give you what data classes do by default. In the next section, you’ll take a look at other alternatives, some of which you may have already encountered.

You must own this product to join the conversation.