Everything else is ready: study the parts, the key terms and the quiz below.
Classes and Objects
Bundle data and behaviour into objects, and read code that does.
In this lesson9 parts
- 01A review in three pieces
- 02class and `__init__`
- 03Methods and `self`
- 04What an object holds
- 05Special methods
- 06Everything is an object
- 07Inheritance
- 08Where classes mislead
- 09Recap, your challenge, and next
Key terms
The words this lesson introduces, each in one line. The module’s glossary collects them all.
self- The first parameter of a method: the object the method was called on.
review.is_positive()isReview.is_positive(review). - attribute
- A value stored on an object, reached with a dot:
review.rating.vars(review)shows an object's attributes as a dictionary. - class
- A definition of a new kind of object:
class Review:. Calling it,Review(...), creates an instance. - inheritance
- Defining a class from another, so that it starts with everything the other has:
class VerifiedReview(Review):. - instance
- An object created from a class:
review = Review("kettle", 5, "…"). - method
- A function defined inside a class, called on an object with a dot:
review.tokens(). - special method
- A method with two underscores on each side of its name, which Python calls itself:
__init__,__repr__,__eq__,__add__. - subclass
- A class defined from a base class:
RatingErroris a subclass ofValueError.
Quiz 5 questions
Your first pick on each question is the one that counts, and a right one earns a coin. Getting one wrong here is how the lesson sticks.
Practice
Problems to solve in your own notebook. Each states the problem, not the steps: working out the steps is the exercise. Level A applies the lesson, B combines it with earlier ones, C stretches it.
The self-checking notebook for this lesson is Notebook 1 · Classes and Dataclasses.
Common mistakes
What you will see when it goes wrong, why it happens, and the fix.
Where it’s used
Where this lesson’s ideas turn up in real work.