Loading video player…

Comparison to Standard Classes

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.

Avatar image for feralfer

feralfer on Sept. 19, 2021

I am very sorry but I have to say that this presentation is unclear with very poor pedagogy. This tuto does not even recall the PEP defining the data classes (557). I better spent my time reading stackoverflow.com/questions/47955263/what-are-data-classes-and-how-are-they-different-from-common-classes

Become a Member to join the conversation.