livepython.net
CHAPTER 20Object-Oriented Programming (Classes)
20.5  INHERITANCE

Python Inheritance: Parent and Child Classes

What Is Inheritance in Python?

Inheritance lets you build a new class from a class that already exists. The new class, the child, gets every method of the old class, the parent, for free. Then you add only what's new.

Think of it like a family recipe. Grandma's cake recipe is the parent. Your chocolate cake starts from her recipe and adds cocoa. You don't copy out the whole recipe again; you write "Grandma's cake, plus cocoa".

PYTHONedit me
class Animal:
    def __init__(self, name):
        self.name = name

    def eat(self):
        print(self.name, "is eating")

class Dog(Animal):
    def fetch(self):
        print(self.name, "fetches the ball")

rocky = Dog("Rocky")
rocky.eat()
rocky.fetch()
OUTPUT
Rocky is eating
Rocky fetches the ball

Dog has no __init__ and no eat() of its own, yet Dog("Rocky") and rocky.eat() work. They come from Animal.

The rules

  • Write the parent's name in brackets: class Dog(Animal):.
  • The child gets all the parent's methods, including __init__ and __str__.
  • The child can add new methods, like fetch().
  • The parent doesn't get the child's methods. An Animal can't fetch.
  • Define the parent first, then the child. Python reads from top to bottom.

Avoid: calling a child's method on a parent object

PYTHONedit me
class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def fetch(self):
        print(self.name, "fetches the ball")

lucky = Animal("Lucky")
lucky.fetch()
OUTPUT
AttributeError: 'Animal' object has no attribute 'fetch'

Inheritance only flows down, from parent to child. lucky is a plain Animal, and fetch() lives in Dog.

Common beginner doubt: "How do I know when to use inheritance?" Use the "is a" test: a dog is an animal, a savings account is a bank account. If the sentence sounds right, inheritance fits.

A child class, like class Dog(Animal):, gets all of the parent's methods and adds its own.

your turnPredict the output

What will this print?

class Vehicle: def start(self): print("Engine on") class Car(Vehicle): def honk(self): print("Beep!") my_car = Car() my_car.start() my_car.honk()
Your turn! What will this code show on the screen?
your turnPick the right idea

Which pair passes the "is a" test, so the first class could inherit from the second?

Think about it, then pick one.

Override a Method in a Child Class

To override a method means to write a method in the child class with the same name as one in the parent. For objects of the child class, the child's version replaces the parent's.

Think of it like a school uniform rule with one exception. Every class wears the school uniform (the parent's rule), but on sports day, the sports team wears its own kit instead (the child's version).

PYTHONedit me
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(self.name, "makes a sound")

class Dog(Animal):
    def speak(self):
        print(self.name, "says Woof!")

class Cat(Animal):
    def speak(self):
        print(self.name, "says Meow!")

class Fish(Animal):
    pass

for pet in [Dog("Rocky"), Cat("Lucky"), Fish("Sunny")]:
    pet.speak()
OUTPUT
Rocky says Woof!
Lucky says Meow!
Sunny makes a sound

How Python finds a method

When you call rocky.speak(), Python looks in two places, in this order:

  1. The object's own class, Dog. Is there a speak()? Run it.
  2. If not, the parent class, Animal.

So Dog and Cat use their own speak(), and Fish, which has none, uses the one from Animal.

  • Override with the exact same name. speaks() would be a new method, not an override.
  • Overriding changes only the child. Animal objects still use the parent's version.
  • __str__ can be overridden too, so each child can print itself its own way.

Common beginner doubt: "Did the loop know which speak() to use?" No, and it didn't need to. Each object knows its own class, so the same call, pet.speak(), does the right thing for each one. Programmers call this polymorphism, a Greek word for "many shapes".

Override a method by writing one with the same name in the child. Python looks in the child first, then the parent.

your turnFill the gap

Complete the child class so it prints: square

class Shape: def name(self): return "shape" class Square(Shape): def ?(self): return "square" print(Square().name())

It should print: square

Which piece makes this code work?
your turnType the output

Type what this prints

class Bird: def move(self): return "flies" class Penguin(Bird): def move(self): return "swims" print(Bird().move(), Penguin().move())
Read the code line by line, then type the output exactly.

Use super() to Call the Parent's __init__

Sometimes a child class needs extra attributes. Then it writes its own __init__, and calls the parent's __init__ with super().__init__(...), so the parent can still set up its part.

Think of it like adding a room to a house. The builder doesn't knock the house down and start again. The main house (the parent's part) stays, and the new room (the child's extra) is built onto it.

PYTHONedit me
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name}, {self.age}"

class Student(Person):
    def __init__(self, name, age, school):
        super().__init__(name, age)
        self.school = school

    def __str__(self):
        return f"{self.name}, {self.age}, studies at {self.school}"

sunny = Person("Sunny", 30)
rocky = Student("Rocky", 15, "Green Valley School")
print(sunny)
print(rocky)
OUTPUT
Sunny, 30
Rocky, 15, studies at Green Valley School

The rules

  • super() means "the parent class". super().__init__(name, age) runs the parent's __init__ for this object.
  • Pass the parent the values it needs. Then set the child's new attributes with self..
  • Call super().__init__() first, at the top of the child's __init__.
  • super() works for other methods too: super().__str__() gives the parent's text, so the child can add to it.

Avoid: forgetting super().__init__()

PYTHONedit me
class Person:
    def __init__(self, name):
        self.name = name

class Student(Person):
    def __init__(self, name, school):
        self.school = school

rocky = Student("Rocky", "Green Valley School")
print(rocky.school)
print(rocky.name)
OUTPUT
Green Valley School
AttributeError: 'Student' object has no attribute 'name'

The child's __init__ overrides the parent's. So the parent's __init__ never ran, and self.name was never set. Every error is a clue: a missing attribute in a child class often means a missing super().__init__().

Common beginner doubt: "Can't I write self.name = name in the child instead?" You could, but then the same line lives in two classes. If the parent's setup changes later, the child would be out of date. Let the parent set up its own part.

A child with extra attributes calls super().__init__(...) first, then sets its own.

your turnFix the code

Fix the code so it prints: Lucky plays guitar

It should print: Lucky plays guitar

class Person:
    def __init__(self, name):
        self.name = name

class Musician(Person):
    def __init__(self, name, instrument):
        self.instrument = instrument

lucky = Musician("Lucky", "guitar")
print(lucky.name, "plays", lucky.instrument)
This code does not work yet. Fix it, then press Run.
your turnPredict the output

What will this print?

class Account: def __init__(self, owner): self.owner = owner def __str__(self): return "Account of " + self.owner class Savings(Account): def __str__(self): return super().__str__() + " (savings)" print(Savings("Sunny"))
Your turn! What will this code show on the screen?

When to Use Inheritance (and When Not To)

Inheritance is great for sharing code between classes that are kinds of the same thing. But not every link between two classes is inheritance. Often, one object simply has another, stored as an attribute.

Think of it like your family and your backpack. You are your parents' child, and you got your eye colour from them. But you have a backpack. Nobody would say you inherited from your backpack.

"Is a" or "has a"?

SentenceLinkIn code
A savings account is a bank accountinheritanceclass SavingsAccount(BankAccount):
A dog is an animalinheritanceclass Dog(Animal):
A student has marksan attributeself.marks = []
A library has booksan attributeself.books = []
PYTHONedit me
class Book:
    def __init__(self, title):
        self.title = title

class Library:
    def __init__(self):
        self.books = []

    def add(self, book):
        self.books.append(book)

shelf = Library()
shelf.add(Book("Python Basics"))
shelf.add(Book("Fun with Loops"))
for book in shelf.books:
    print(book.title)
print(len(shelf.books), "books")
OUTPUT
Python Basics
Fun with Loops
2 books

A library isn't a kind of book, so Library doesn't inherit from Book. It keeps its books in a list attribute instead.

isinstance() and inheritance

A child object counts as its parent's type too, because a dog is an animal:

PYTHONedit me
class Animal:
    pass

class Dog(Animal):
    pass

rocky = Dog()
print(isinstance(rocky, Dog))
print(isinstance(rocky, Animal))
print(isinstance(Animal(), Dog))
OUTPUT
True
True
False

Keep it gentle

  • One level of inheritance is plenty for most programs: one parent and a few children.
  • Put the shared code in the parent, and only the differences in each child.
  • Copying the same methods into two classes? Ask: is one a kind of the other, or are both kinds of a new parent?

Use inheritance when the child is a kind of the parent. When one thing has another, use an attribute.

your turnPick the right idea

A car has an engine. How should you link a Car class and an Engine class?

Think about it, then pick one.
your turnPredict the output

Remember the math module?

import math print(math.sqrt(16)) print(math.floor(7.9))
Your turn! What will this code show on the screen?

Practice: Inheritance

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 188.Python Program to Make Animal Classes Using InheritanceMediumSolve
  2. 189.Python Program to Build a Bank with Savings AccountsHardSolve