Part 4 of 6 · Chapter 3 of 4

Bundling Data With Behaviour

A dictionary can hold a name and an age, but nothing stops you misspelling the key next time you use it. Define a class once, stamp out three objects from it, and give each its own values without repeating the shape.

Intermediate11 min read

Worth reading first: Looking Things Up Instead of Counting Along


A dictionary can hold a name and a grade, but nothing stops you misspelling the key next time you use it. Define a class once, stamp out three objects from it, and give each its own values without repeating the shape.

A blueprint, and the objects made from it

class Student: defines a shape, not a value. Nothing exists yet until you call it like a function — Student("Ada", 92) — which creates one actual object, called an instance, following that shape.

class Student:
class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

No objects yet — the class itself is just a blueprint. Click the button to stamp one out.

self is the object talking about itself

Inside the class, self refers to whichever instance is currently being worked on. self.name = namemeans “store this particular call's name on this particular object”, not on the class itself.

Terminal
$ >>> ada = Student("Ada", 92)$ >>> grace = Student("Grace", 88)$ >>> ada.name$ 'Ada'$ >>> grace.name$ 'Grace'

Python passes the object in as self automatically every time you call a method on it — you never pass it yourself. That is the entire reason every method you define takes self as its first parameter.

Bundling data and the functions that act on it

A class can hold functions as well as data, and those functions automatically get access to that object's own values through self.

Terminal
$ >>> class Student:$ ...     def __init__(self, name, grade):$ ...         self.name = name$ ...         self.grade = grade$ ...     def passed(self):$ ...         return self.grade >= 60$ ...$ >>> ada = Student("Ada", 92)$ >>> ada.passed()$ True

Key takeaways

  • A class is a blueprint. Calling it like a function creates one instance following that blueprint.
  • self refers to the specific instance a method is currently running on, and Python passes it in automatically.
  • self.name = name stores a value on that instance, not on the class — every instance gets its own copy.
  • A class bundles data with the functions that act on it, which a plain dictionary cannot enforce the shape of.