Skip to the workspace
Pebellslearn by building
Objects  ›  Lesson

Classes & Instances

Classes 19 minA class defines the behavior and construction of a kind of object. An instance is an individual object created from that class.

A class defines the behavior and construction of a kind of object. An instance is an individual object created from that class.

Create independent instances, change their attributes and distinguish a new object from an alias of an existing one.

The next question is what Python does with ada.deposit(50): where does self come from, which balance changes, and where is that balance kept after the call ends? Start with the thermostat's state, then separate three things that are easy to blur together: a class, one instance, and a name referring to that instance.

A cookie-cutter labelled "class Account" stamping out two separate cookies: one iced "owner: Ada, balance: 100", the other "owner: Bea, balance: 20" — the same shape, independent fillings

Open a bank account

A bank account needs an owner and a balance, plus a way to add money. Data and the function that changes it, bundled into one template:

python

For these ordinary classes, calling Account("Ada", 100) creates an instance, runs __init__ with that instance as self, then gives the instance to the caller. Only after that call finishes is ada assigned. __init__ initializes an object that already exists; it must return None, not the new object.

Read self.owner = owner in two halves. The right-hand owner is a parameter of this call. The left-hand self.owner is an attribute on the object. A plain owner = owner would only reassign a local name and would create no attribute.

ada.deposit(50) finds the method and supplies ada as its first argument. For this class it has the same effect as Account.deposit(ada, 50). The body reads ada.balance, adds 50, and stores 150 back on that object. The method falls off the end and returns None; result = ada.deposit(50) would therefore bind result to None while changing the balance. Revisit return values if those two outcomes feel contradictory.

Forget self in the signature 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.

Preparing this topic’s interactive investigation…

Two accounts, two balances

Each constructor call creates a distinct account. In this example each account has a balance attribute, and a deposit reassigns that attribute on only one account. Separate dictionaries can also hold separate state; a class additionally gives these accounts named operations such as deposit.

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 self bind to a different object on each call, side by side:

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)

New instance, alias, or shared contents?

Different object identities do not guarantee different objects at the end of every attribute. Attribute assignment stores a reference; it does not copy the value. Predict the two printed lists before running this:

python

The is operator asks whether two references identify the same object. The first line is False True: two baskets, but alias names the first basket. Both basket attributes refer to the one source list, so both printed lists contain bread. The relationship is a → basket A → source list and b → basket B → same source list; alias is a second route to basket A.

Change the setup to self.items = list(items) and rerun. It now builds a new outer list for each basket, so appending through one basket leaves the other alone. This is a shallow copy: if the items themselves were dictionaries, those inner dictionaries would still be shared. The later identity and aliasing lesson develops that distinction.

One more change tests a different idea: keep the original setup, but replace alias.items.append("bread") with alias.items = ["bread"]. This reassigns one basket's attribute instead of mutating the shared list. Work out which of a, b, and source now sees which list before running it.

Stock a shopping basket

Methods aren't only for mutating — a method can just as well read self and hand back an answer, no arguments needed beyond the object itself:

python

summary() reads like a question you'd ask the object, because everything it needs is already attached to self. Now the trap: put that empty list on the class instead of inside __init__, and every basket shares the same one.

What does this print?
class Basket:
    items = []          # created ONCE, shared by every basket

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

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

Before the practice, try a Basket with a class attribute items = [], then set a.items = [] on only one instance. a now has an instance attribute that hides the class attribute; b still finds the class list. This explains why assigning an attribute and mutating an object reached through an attribute can behave differently. The Python class tutorial documents both lookup and the shared-list trap.

Quick practice

What does this print?
class Counter:
    def __init__(self):
        self.n = 0

    def bump(self):
        self.n += 1
        return self.n

c1 = Counter()
c2 = Counter()
c1.bump()
c1.bump()
print(c1.n, c2.n)
What does this print?
class Rectangle:
    def __init__(self, w, h):
        self.w = w
        self.h = h

    def area(self):
        return self.w * self.h

print(Rectangle(3, 4).area())
broken — fix itNameError

Run it, read the error, then print the point's total without inventing a name that doesn't exist.


🎯 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.

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from one point to a full day at the bank.

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.

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
Project context and further resources
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.
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.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.