Skip to the workspace
Pebellslearn by building
Objects  ›  Lesson

Inheritance

Inheritance 20 minInheritance lets a class obtain and specialize behavior from another class through Python’s method lookup rules.

Inheritance lets a class obtain and specialize behavior from another class through Python’s method lookup rules.

Extend or replace methods, use super deliberately and follow operations on the same instance through the lookup order.

A savings account needs the existing account operations plus interest. Inheritance lets its class reuse method definitions through a lookup relationship. It does not create a second, hidden account inside the savings object. Keep the meaning of self in view: inherited and new methods will receive the same instance, even when their source lives in different classes.

A parent box "Account" (__init__, deposit) above a child box "SavingsAccount" (+rate, +add_interest()); a curved arrow labelled super().__init__(owner, balance) runs from the child's __init__ up into the parent's, and a dashed arrow labelled "deposit() — inherited, unchanged" runs straight down past the child

A savings account, almost for free

The bank wants a savings account. It behaves exactly like the account already built — same owner, same balance, same deposit — plus interest. Copy-pasting the class means every future fix to deposit has to be made twice. Inheritance says it differently: a savings account is an account, with one addition.

python

SavingsAccount never defines __init__ or deposit. Python searches its base class and finds those methods on Account. Inherited __init__ creates the owner and balance attributes on the savings instance; the attributes are not copied from a separate parent object.

Follow the amounts in order: setup stores 100, inherited deposit(100) stores 200, then add_interest(0.1) adds 20 and stores 220. All three operations reach the same s.balance. Writing down this sequence is a useful way to find a wrong rate or an interest call applied before the deposit.

Preparing this topic’s interactive investigation…

Extending the setup with super()

When the child defines its own __init__, that method is the one Python calls. The base setup is not automatically run as a second step. This initializer calls super().__init__ to establish the base fields, then adds its own rate:

python

Skip that super() call and the parent's setup never runs — so whatever attributes it would have created simply don't exist:

broken — fix itAttributeError

Run it and read the error — it's telling you an attribute is missing. Then make it print 0.

Override: replace, or build on

A child can redefine a method outright, or reuse the parent's result and decorate it:

python

Here super().summary() finds Account.summary and calls it with the same savings instance. The child then adds text to the returned string. A change to that base implementation reaches subclasses that inherit it or call it this way. A subclass that completely overrides the method does not automatically run the base method.

Watch the same call, summary(), resolve to different code depending on which object it's called on:

step through it
1class Account:
2 def summary(self):
3 return "account"
4 
5class Savings(Account):
6 def summary(self):
7 return super().summary() + " (savings)"
8 
9a = Account()
10s = Savings()
11a_summary = a.summary()
12s_summary = s.summary()

Follow the lookup order, not a second object

For Savings().summary(), the lookup begins on Savings. Inside that method, self.summary() would start there again and recurse. super().summary() instead continues searching after the class containing this method in the instance type's method resolution order, or MRO. With one base class that is usually the parent. With multiple inheritance it can be a sibling in that order.

This optional example makes that distinction observable without adding state:

python

The order is Combined, Audit, Cache, Base, object; the result is audit>cache>base. In Audit.label, super() reaches Cache, even though Audit directly names Base as its parent. Every method still receives the one Combined instance. These methods cooperate by accepting compatible arguments and continuing the chain. Calling Base.label(self) directly would skip Cache. The documented super behavior is about this ordered search.

Inheritance also creates an expectation for callers. If Account.deposit(50) means “increase the balance by 50,” a subclass that silently deducts a fee inside deposit changes that contract. Sharing code is not sufficient reason to claim the subclass can replace an account in every caller. A fee policy held as an attribute and consulted explicitly is another design: one object has a policy, instead of claiming it is an account subtype.

Before the practice, make Savings.summary() show both a base summary and its rate. Check a plain account and savings account through the same caller. Then temporarily replace super().summary() with self.summary() and explain the resulting repeated call using the lookup order, not “Python got confused.”

Quick practice

What does this print?
class Shape:
    def __init__(self, name):
        self.name = name

class Square(Shape):
    def __init__(self, side):
        super().__init__("square")
        self.side = side

sq = Square(4)
print(sq.name, sq.side)
What happens when you run this?
class Greeter:
    def hello(self):
        return "Hi"

class LoudGreeter(Greeter):
    def hello(self):
        return self.hello() + "!"

print(LoudGreeter().hello())
broken — fix itAttributeError

Run it and read the error. Then let Manager keep the parent's setup as well as its own.


🎯 Your turn

Define Account with deposit(amount), then SavingsAccount(Account) adding a rate and add_interest(). Write savings_after(start, rate, years) applying interest once per year and returning the balance rounded to two decimals:

  • savings_after(100, 0.1, 2) → 121.0
  • savings_after(100, 0.1, 0) → 100.0

Hint — super().__init__(owner, balance) first, then self.rate. Round only at the very end.

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below builds a whole family of accounts sharing one interface — the next lesson's subject.

Your task
Define Account with deposit(amount), then SavingsAccount(Account) adding add_interest() which increases the balance by its rate. Write savings_after(start, rate, years) which applies interest once per year and returns the balance rounded to 2 decimals. Example: savings_after(100, 0.1, 2) → 121.0.

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 subclass that adds one thing

Define Animal with a name and a speak() returning "...". Define Dog(Animal) overriding speak() to return "Woof". Write dog_says(name) returning what a Dog says.

inheritance
DrillExtending the parent's setup

Define Vehicle storing wheels. Define Car(Vehicle) whose __init__ calls super().__init__(4) and also stores brand. Write car_wheels(brand) returning the wheel count.

inheritancesuper
BuildOne loop, several types

Given Cat and Cow both with speak() ("Meow" / "Moo"), write chorus() returning "Meow Moo" by looping over a list holding one of each and joining what they say. The loop must not check which type it has.

polymorphismloop
BossOverride, then call up

Define Logger with line(msg) returning msg. Define Loud(Logger) whose line returns the parent's result upper-cased with "!" appended. Write shout(msg) returning Loud().line(msg).

inheritancesuperoverride
CapstoneTwo accounts, one interface

Define Account(balance) with monthly() returning the balance unchanged, and Savings(Account) whose monthly() adds 1% . Write year_end(balances) where each entry is ["plain", 100] or ["savings", 100], applying monthly() twelve times to each and returning the list of balances rounded to 2 decimals.

inheritancepolymorphismsuperloop
Project context and further resources
You're building a piece ofA bank account that can't go wrong
This piece — SavingsAccount: Everything an account does, plus interest.
Scenario The bank launches a savings product. It behaves exactly like a current account, plus interest — and nobody wants to rewrite deposit().
savings_after.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
savings_after(start, rate, years) → floatCompound the interest once per year; 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.