Module 10 · Lesson 03
Inheritance and Method Overriding
Build classes on top of other classes: inherit attributes and methods, override what differs, extend a parent's method with super(), and treat related objects the same way.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Build a child class
- Override a method
- Extend with super()
- Watch an account get set up
Classes built on classes
A child class starts with everything its parent has, then adds or changes what it needs.
Child(Parent)
class Dog(Animal):gives Dog every attribute and method of Animal.Override
Write a method with the same name in the child to replace the parent's version.
super()
super().__init__(name)runs the parent's setup before the child adds its own.is-a
A Dog is an Animal, so
isinstance(rex, Animal)is True.
Families everywhere
Whenever several kinds of thing share a core, a parent class can hold that core.
- Game enemiesEvery enemy moves and takes damage; a Boss adds a special attack.
- Shop productsBooks, shirts and games are all Products with a price, plus extras of their own.
- School peopleStudents and teachers are both People with a name; each adds different details.
- Drawing appsCircle and Square both come from Shape, and each knows its own
area().
Naming a parent
This line makes a new class from an old one. Tap each part to see its job.
Part 1 of 4
class:Starts a new class, as usual.
Build class families
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Inherit
The child has no code of its own, yet it can do everything the parent can.
Your turn: Add a method purr() to Cat only. Can a plain Pet("Rex") purr?
class Pet:
def __init__(self, name):
self.name = name
def hello(self):
return "Hi, I am " + self.name
class Cat(Pet):
pass
tom = Cat("Tom")
print(tom.hello())Press Run to see what it prints.Watch an account get set up
Press Step to run one line at a time. Watch which class's code is running.
Ready. Press Step to run the first line.
- class Account:
- def __init__(self, owner):
- self.owner = owner
- self.balance = 0
- class Savings(Account):
- def __init__(self, owner, rate):
- super().__init__(owner)
- self.rate = rate
- s = Savings("Ana", 0.05)
- print(s.owner, s.balance, s.rate)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Two levels up:
class A:
def who(self):
return "A"
class B(A):
pass
class C(B):
pass
print(C().who())0 of 6 answered
Common inheritance misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
class Parent:
def __init__(self, a):
self.a = a
def greet(self):
return "hello"
class Child(Parent): # inherit
def __init__(self, a, b):
super().__init__(a) # run the parent's setup
self.b = b
def greet(self): # override
return super().greet() + "!" # extend the parent's version
isinstance(Child(1, 2), Parent) # True
issubclass(Child, Parent) # TruePress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Shapes that share an interface
Model circles and rectangles as kinds of Shape. Every shape has a name and an area method, and a shared describe method uses the area. Print a description of each shape and the largest one.
class Shape:
def __init__(self, name):
self.name = name
def area(self):
raise NotImplementedError("each shape must define area")
def describe(self):
return f"{self.name}: area {self.area():.1f}"
class Circle(Shape):
def __init__(self, radius):
super().__init__("circle")
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height):
super().__init__("rectangle")
self.width = width
self.height = height
def area(self):
return self.width * self.height
shapes = [Circle(2), Rectangle(3, 5), Circle(1)]
for shape in shapes:
print(shape.describe())
print("Largest:", max(shapes, key=lambda s: s.area()).name)Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Forgetting super().__init__
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
class Vehicle:
def __init__(self, wheels):
self.wheels = wheels
class Bike(Vehicle):
def __init__(self, gears):
self.gears = gears
print(Bike(21).wheels)Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Software as a service
Notification channels
A project tool sends alerts by email, by text message and inside the app. All channels share the same formatting and logging; each channel only defines how a message is delivered.
Why Python fits
notifylives in the parent and callsformatanddeliver, which each child can override. The SMS channel shortens messages by extending the parent'sformatwithsuper(). Adding a new channel means writing one small class; the notify logic never changes.Pythonclass Channel: def __init__(self, user): self.user = user self.sent = [] def format(self, event): return f"[{event['level'].upper()}] {event['text']}" def deliver(self, message): raise NotImplementedError def notify(self, event): message = self.format(event) self.sent.append(self.deliver(message)) class Email(Channel): def deliver(self, message): return f"email to {self.user}@example.com: {message}" class Sms(Channel): def format(self, event): return super().format(event)[:30] def deliver(self, message): return f"sms to {self.user}: {message}" event = {"level": "warn", "text": "Build 412 failed on the main branch"} for channel in [Email("ana"), Sms("ben")]: channel.notify(event) print(channel.sent[-1])OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Can a class inherit from more than one parent?
Do I need super() if the child has no __init__?
How do I see which classes a class inherits from?
Can a child remove a method it inherited?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 13 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.