Chapter Eleven · Data That Knows What to Do
Objects and Classes
Every value in Python is an object: data bundled with the things it can do. This chapter shows how to define your own kind of object with a class, how dataclasses write the tedious parts for you, and, just as important, when a plain dictionary is the better choice.
Since Chapter 2 you have been using objects without the word: every time you wrote a dot, as in text.upper() or todo.append("milk"), you asked an object to do something. A string knows how to make an upper-case copy of itself; a list knows how to grow. This chapter lets you make your own kinds of object.
Three topics, deliberately few. Classes: how to define one, what self means, and how methods work. Dataclasses: the short way to write the most common kind of class, a record with named fields. And an honest rule of thumb for choosing between a class, a dataclass and the dictionaries you already know, because a beginner's most common mistake with classes is using them where nothing needed one.
Topics in This Chapter
__init__, what self refers to, methods that change an object, and a readable printout.