Pebellslearn by building
0%
RoadmapMatrixCatalogSandboxSign in
Objects  ›  Lesson

Classes & Instances

Classes 15 minBundling data with the functions that belong to it
You're building a piece ofA bank account that can't go wrong
This piece — Account: Holds an owner and a balance, and knows how to deposit.
Scenario A new customer opens an account and pays in twice on the first day. The bank needs the closing balance.
Your task
Define an Account class with __init__(self, owner, balance=0) and a deposit(self, amount) method, then build account_balance(owner, deposits) which opens an account and deposits each amount in turn, returning the final balance. Example: account_balance("Ada", [100, 50]) → 150.

Classes & Instances

Everything you've built so far keeps data on one side and functions on the other. A dict holds the account; separate functions do things to it. That works right up until the moment someone forgets to call the checking function.

Objects close that gap. A class is a template that bundles data with the functions allowed to touch it — and once they live together, you can start making promises about the data that the rest of the program cannot break.

We'll build a bank account across this section. This lesson gets it opened.


A class is a template; an instance is a thing

python

__init__ runs automatically when you call Account("Ada", 100). It isn't the constructor exactly — the object already exists by then — it's the setup, the place you hang values off it.

self is the object being worked on

This is the part that feels strange coming from other languages, so let's be blunt about it: self is just the first parameter, and Python passes it for you. ada.deposit(50) is really Account.deposit(ada, 50).

python

Notice deposit returns nothing. It doesn't need to — it changed the object, and the object is what everyone is holding.

Forget self and the error is confusing, so meet it now:

broken — fix itTypeError

Run it and read the error carefully. It's counting arguments. Then fix the signature.

Each instance has its own state

This is the whole reason to bother:

What does this print?
class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

a = Account("Ada")
b = Account("Bea")
a.deposit(100)
print(b.balance)

Watch two accounts live side by side, and see self bind to a different object on each call:

step through it
1class Account:
2 def __init__(self, owner, balance=0):
3 self.owner = owner
4 self.balance = balance
5 
6 def deposit(self, amount):
7 self.balance += amount
8 
9a = Account("Ada")
10b = Account("Bea", 20)
11a.deposit(100)
12b.deposit(5)
13print(a.balance, b.balance)

Methods can return things too

deposit mutates. A method can just as well compute and hand something back:

python

summary() takes no arguments beyond self because everything it needs is already attached. That's the shape you're aiming for — methods that read like questions you'd ask the object.

One trap worth avoiding today

Attributes belong in __init__, not on the class body, whenever they're mutable:

What does this print?
class Basket:
    items = []          # shared by EVERY basket

    def add(self, thing):
        self.items.append(thing)

a = Basket()
b = Basket()
a.add("soup")
print(len(b.items))

🎯 Your turn

Define an Account class with __init__(self, owner, balance=0) and a deposit(self, amount) method. Then write account_balance(owner, deposits) which opens an account, deposits each amount in turn, and returns the balance:

  • account_balance("Ada", [100, 50])150
  • account_balance("Sam", [])0

Hint — store self.owner and self.balance in __init__; deposit is one line; build the account once and loop.

Then press ▶ Run and hit ✓ Check. ✅

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upA point that reports itself

Define a Point class taking x and y, then write point_sum(x, y) returning p.x + p.y for a Point you build inside.

classes__init__
DrillA counter that remembers

Define a Counter class starting at 0 with a bump() method that adds 1. Write count_to(n) which bumps n times and returns the count. The point: the object remembers between calls.

classesstatemethods
BuildArea from a method

Define a Rectangle with width and height and an area() method returning the area. Write area_of(w, h) that builds one and returns r.area().

classesmethodsreturn
BossA basket that totals itself

Define a Basket that starts empty, with add(price) and total(). Write basket_total(prices) adding every price and returning the total.

classeslistloopmethods
CapstoneA day at the bank

Define an Account with owner, balance, and deposit(amount). Write day_summary(owner, deposits) returning {"owner": ..., "balance": ..., "count": ...} — the owner, the closing balance, and how many deposits were made.

classesmethodsloopdict
account_balance.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
account_balance(owner, deposits) → floatOpen an account and deposit each amount; return the balance.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.