Section · 01
What a class actually is
A class is a template you define. Instances are the actual objects you create from that template. Same idea as “a recipe” vs “a meal cooked from that recipe” — one shape, many servings, each with its own state.
# Define the class once...
class Stopwatch:
pass
# ...then create as many instances as you want
sw1 = Stopwatch()
sw2 = Stopwatch()
sw3 = Stopwatch()
print(type(sw1)) # <class '__main__.Stopwatch'>
print(sw1 is sw2) # False — different objectsThat class is useless right now (the body is just pass, which means “no content”), but the shape is real. Three things to notice:
1. The class keyword introduces a definition. Class names use CapWords.
2. Calling the class — Stopwatch() — creates an instance.
3. Each instance is a distinct object, even if they look identical.Section · 02
A class with state and behavior
Real classes have attributes (data on each instance) and methods(functions that work on an instance). Here’s a small but actually useful one:
class Counter:
def __init__(self, start=0):
self.value = start # an attribute on this instance
def increment(self, by=1): # a method
self.value = self.value + by
def reset(self):
self.value = 0
# Use it
page_views = Counter()
page_views.increment()
page_views.increment()
page_views.increment(by=5)
print(page_views.value) # 7
# A second counter is completely independent
errors = Counter(start=100)
print(errors.value) # 100We’ll break down __init__, self, and the rest in the next two lessons. The point here is the shape: a class defines what data each instance carries and what each instance can do. The instances are where the actual work happens.
Section · 03
When (not) to use a class
Classes are a tool, not a default. Plenty of Python programs are better as a flat module of functions plus a few dicts. Reach for a class when one of these is true:
1. The same data and behavior travel together.
A shopping cart has items, a total, and a checkout method. Pulling those apart across loose functions and a dict gets ugly fast. A Cart class keeps them bound.
2. You need many instances of the same shape.
One user object is a dict. Ten thousand user objects with the same fields and the same methods are a class.
3. There's invariant you want to enforce.
Your account balance should never go negative. A dict can’t enforce that — anyone can write account["balance"] = -500. A class with a withdraw() method can reject the operation.
When NOT to bother
# Don't write a class for this:
class Greeter:
def greet(self, name):
print(f"Hi, {name}.")
# Just write a function:
def greet(name):
print(f"Hi, {name}.")If a “class” only ever holds one method and no state, it’s a function pretending to be something more. Don’t pretend.
Section · 04
Class vs dict — and why classes win at scale
You could model an order as a dict:
order = {
"id": "A-1042",
"items": [...],
"subtotal": 89.50,
"discount": 0.10,
}
# To do anything with it, you write a function that takes the dict:
def apply_discount(order):
return order["subtotal"] * (1 - order["discount"])
apply_discount(order)Now scale that up. You have 12 order-related functions floating in a file. Every one starts with “is this dict shaped right?” You have to remember which fields are required, which are optional, what the keys are named. Renaming a key means hunting through every function. A typo in order["subbtotal"] fails at runtime, not at write time.
Same idea as a class:
class Order:
def __init__(self, id, items, subtotal, discount=0.0):
self.id = id
self.items = items
self.subtotal = subtotal
self.discount = discount
def discounted_total(self):
return self.subtotal * (1 - self.discount)
order = Order(id="A-1042", items=[...], subtotal=89.50, discount=0.10)
order.discounted_total()The shape is declared once, in one place. Typos are caught earlier (most editors will autocomplete order.discount but not order.discoumt). The behavior lives next to the data it operates on. You traded a small amount of upfront structure for a big drop in maintenance pain.
The next two lessons go deeper: __init__ and attributes, then methods and self.