Skip to contentSkip to navigation

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

Tap any part of the code below, or press Next.1 of 4 explored

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?

Python
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())
Output
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.

  1. class Account:
  2. def __init__(self, owner):
  3. self.owner = owner
  4. self.balance = 0
  5. class Savings(Account):
  6. def __init__(self, owner, rate):
  7. super().__init__(owner)
  8. self.rate = rate
  9. s = Savings("Ana", 0.05)
  10. 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 notesOpen

A class built on another

Put the name of an existing class in brackets after a new class's name, and the new class inherits from it:

Try it 1: edit me, then Run
class Animal:
    def __init__(self, name):
        self.name = name

    def describe(self):
        return f"{self.name} is an animal"

    def speak(self):
        return "..."

class Dog(Animal):
    def speak(self):
        return "Woof"

rex = Dog("Rex")
print(rex.describe())    # Rex is an animal
print(rex.speak())       # Woof
Output
Press Run to see what it prints.

Animal is the parent (also called the base class or superclass) and Dog is the child (subclass). Dog has no __init__ or describe of its own, yet Dog("Rex") and rex.describe() work, because the child inherits everything the parent defines.

When you call a method, Python looks for it on the object's own class first, then on the parent, then on the parent's parent, and so on. That search order is why rex.speak() finds Dog.speak, while rex.describe() finds Animal.describe.

Overriding a method

Defining a method with the same name in the child overrides the parent's version for objects of the child class. Dog.speak overrides Animal.speak. Parent objects are not affected: Animal("Generic").speak() still returns "...".

is-a relationships

Inheritance means "is a kind of". A dog is a kind of animal, so Dog(Animal) makes sense, and every Dog object is also an Animal:

Try it 2: edit me, then Run
print(isinstance(rex, Dog))        # True
print(isinstance(rex, Animal))     # True
print(issubclass(Dog, Animal))     # True
print(isinstance(Animal("x"), Dog))  # False
Output
Press Run to see what it prints.

The relationship only goes one way: an animal is not necessarily a dog. Every class you write also inherits, in the end, from Python's built-in object, which provides defaults such as the plain __repr__.

Extending the parent with super()

Often a child needs everything the parent's __init__ does, plus a little more. Instead of copying the parent's lines, call it with super():

Try it 3: edit me, then Run
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def yearly_cost(self):
        return self.salary

class Manager(Employee):
    def __init__(self, name, salary, bonus):
        super().__init__(name, salary)   # parent sets name and salary
        self.bonus = bonus               # child adds its own attribute

    def yearly_cost(self):
        return super().yearly_cost() + self.bonus

boss = Manager("Ana", 50000, 8000)
print(boss.name, boss.yearly_cost())     # Ana 58000
Output
Press Run to see what it prints.

super() means "the parent class, for this object". super().__init__(name, salary) runs Employee.__init__ on the new manager, so the shared setup lives in one place. If you change how employees store their salary, managers pick up the change automatically.

The second override, yearly_cost, also builds on the parent: it asks the parent for the basic cost and adds the bonus. This "do what the parent does, then a bit more" pattern is the most common use of super().

If a child defines its own __init__ and forgets to call super().__init__, the parent's setup never runs, and attributes like self.name are missing.

One loop, many kinds of object

Because every object in a family has the same methods, code can use them without knowing which subclass it has:

Try it 4: edit me, then Run
staff = [Employee("Ben", 30000), Manager("Ana", 50000, 8000)]
total = sum(person.yearly_cost() for person in staff)
print(total)                              # 88000
Output
Press Run to see what it prints.

Each object answers yearly_cost() in its own way. This is called polymorphism: one interface, many forms. You have used it already: len() works on strings, lists and dictionaries, which each measure themselves differently. With polymorphism you add a new kind of object, such as a Contractor, without touching the loop.

A parent can also define a method that every child is expected to override, and raise NotImplementedError in its own version, so a forgotten override fails loudly instead of quietly doing nothing.

Several levels

Inheritance can go several levels deep: class Puppy(Dog) inherits from Dog, which inherits from Animal. Keep families shallow, usually one or two levels. Deep chains are hard to follow, because understanding one method may mean reading four classes.

Inheritance or composition?

Use inheritance only for true "is a kind of" relationships. If the honest description is "has a", use an attribute instead, which is called composition: a car has an engine, so give Car an engine attribute holding an Engine object, rather than class Car(Engine). Composition is often the more flexible choice, because the parts can be swapped or shared, and many experienced programmers reach for it first.

Syntax

The general shape of the statements in this lesson.

syntax.py
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)            # True
Output
Press 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

Beginner

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.

Python
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)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

describe is written once in Shape, but each call to self.area() runs the child's own version. The parent's area raises NotImplementedError, so a new shape that forgets to define it fails clearly. max works with any mix of shapes, because they all have area.

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.

Buggy code: run it
class Vehicle:
    def __init__(self, wheels):
        self.wheels = wheels

class Bike(Vehicle):
    def __init__(self, gears):
        self.gears = gears

print(Bike(21).wheels)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

AttributeError: 'Bike' object has no attribute 'wheels'

Write this instead

class Bike(Vehicle):
    def __init__(self, gears):
        super().__init__(2)
        self.gears = gears

Why it happens

Bike's own __init__ replaces the parent's, so Vehicle.__init__ never runs unless it is called.

In the real world

Where this shows up in software people use every day.

  1. Notification channels

    Software as a service

    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

    notify lives in the parent and calls format and deliver, which each child can override. The SMS channel shortens messages by extending the parent's format with super(). Adding a new channel means writing one small class; the notify logic never changes.

    Python
    class 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])
    Output
    Press 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?

Yes, Python allows multiple inheritance, as in class C(A, B). It has subtle rules about which method wins; the Python in Depth course covers them. Single inheritance is enough for most programs.

Do I need super() if the child has no __init__?

No. A child without its own __init__ simply inherits the parent's, which runs automatically.

How do I see which classes a class inherits from?

Dog.__mro__ lists the classes Python searches, in order, ending with object. It is a quick way to check the search order when a method does something unexpected.

Can a child remove a method it inherited?

Not really. If a child would need to remove parent behaviour, that is a sign the is-a relationship is wrong, and composition is probably the better design.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

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.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

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.