Classes & Objects
Lesson 4 of 6 · View course roadmap
Learn the idea
A class is a blueprint; an object (instance) is a thing built from it. Classes bundle data (attributes) with behaviour (methods):
__init__— the constructor, runs when you create an instanceself— the instance itself; every method receives it firstself.name = name— stores data on the instance
Think of Dog as the cookie cutter and each Dog("Rex") as a cookie. Classes shine when data and the functions that operate on it belong together — a bank account with balance + deposit/withdraw, a player with health + damage logic.
Where you'll use this
Django models, game entities, GUI widgets, bank accounts — anywhere data and behaviour travel together, there's a class. Frameworks hand you base classes and your entire job is filling in methods.
Common mistakes
- Forgetting
selfin the method signature → 'takes 0 positional arguments but 1 was given', the most-googled Python error. - Writing
name = nameinstead ofself.name = namein __init__ — the data vanishes when the method ends. - Class-level mutable attributes shared by every instance — define per-instance data inside __init__, not in the class body.
Pro tip
For data-carrying classes, @dataclass writes __init__, __repr__ and __eq__ for you: @dataclass class Point: x: int; y: int. Modern Python uses it constantly.
Watch how it runs — line by line
Press play to watch Python execute this code, one line at a time.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +35 XP
Create a class BankAccount with __init__(self, owner) starting balance 0, a deposit(amount) method, and a report() method returning "{owner}: {balance}". Create an account for "Simas", deposit 50 then 25, and print the report.
Simas: 75
self.balance = 0 in __init__; deposit does self.balance += amount.
class BankAccount:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
self.balance += amount
def report(self):
return f"{self.owner}: {self.balance}"
acct = BankAccount("Simas")
acct.deposit(50)
acct.deposit(25)
print(acct.report())
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.