Getting Started with Classes
Introduction: Why Classes?
Welcome to Getting Started with Classes in Python! This is the very first unit of the course, so we are starting right at the foundation: teaching Python how to describe a kind of thing.
Suppose we want to keep track of two dogs. With plain variables, we might write something like this:
Nothing here is wrong, but nothing ties rex_name to rex_age either. Python sees six unrelated variables, and adding a third dog means three more names to invent and keep straight. Classes fix this by letting us group related data under a single object. In this lesson, we will define a class, create objects from it, and store data on each one.
Blueprint vs. Object: The Core Mental Model
Before writing any code, let's establish the mental model, because the rest of this learning path relies on it constantly.
Think of a cookie cutter and the cookies it produces. The cutter defines the shape; it is not itself something we eat. Each cookie we press out is a separate, real object that happens to share that shape. Another way to picture it is as a blank form template versus the filled-in forms sitting in a folder.
In Python vocabulary:
- A class is the blueprint: it defines the structure and the "kind" of thing we are making.
- An instance (also called an object) is a real thing built from that blueprint. In this lesson, we will use instances to hold the unique data—like a specific name or age—that belongs to an individual dog.
So one Dog class can produce as many individual dogs as we like, each carrying its own name, breed, and age.
Defining a Minimal Class with class and pass
Let's write the smallest class Python allows:
Every piece matters here:
classis the keyword that tells Python we are defining a new kind of object.Dogis the class name. By convention, class names useCapitalizedWords, which visually separates them from variables and functions.- The colon opens a block, and everything belonging to the class must be indented underneath it.
passis a placeholder that means "intentionally nothing here." Python requires at least one statement in the block, and withoutpasswe would get anIndentationError.
Notice that running this code creates zero dogs. It only teaches Python what the word Dog means.
