Python 6.1Code walkthrough9 parts

Classes and Objects

Bundle data and behaviour into objects, and read code that does.

Loading your progress…Next: 6.2 Dataclasses

In this lesson9 parts

  1. 01A review in three pieces
  2. 02class and `__init__`
  3. 03Methods and `self`
  4. 04What an object holds
  5. 05Special methods
  6. 06Everything is an object
  7. 07Inheritance
  8. 08Where classes mislead
  9. 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() is Review.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: RatingError is a subclass of ValueError.

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.