Velamuvi AIAcademy

Lesson 9 of 15 · Relationships

Inheritance

Learn Python inheritance with simple definitions and examples: parent and child classes, the is-a relationship, isinstance(), issubclass() and inheritance chains.

  • 8 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • What inheritance is and why it saves you work
  • How to create a child class from a parent class
  • How to add new methods to a child class
  • How to check types with isinstance() and issubclass()
  • When inheritance is the right choice

The problem: copying the same code

Imagine an app for a pet clinic. Dogs and cats both have a name and an age, and both can eat and sleep. Only a few things are different: dogs bark, cats meow.

If you wrote two separate classes, you would copy the name, age, eating and sleeping code into both. Every bug fix would have to be made twice. Inheritance lets you write the shared part once.

Think of a family recipe. A child learns the parent's recipe as it is, and can then add a new ingredient of their own. They do not need to rewrite the whole recipe.

Writing a child class

Put the parent's name in brackets after the child's name: class Dog(Animal):.

Try it yourselfPython
class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def eat(self):
        return f"{self.name} is eating"

    def sleep(self):
        return f"{self.name} is sleeping"


class Dog(Animal):
    def bark(self):
        return f"{self.name} says Woof!"


class Cat(Animal):
    def meow(self):
        return f"{self.name} says Meow!"


rex = Dog("Rex", 3)
tom = Cat("Tom", 5)

print(rex.eat())
print(rex.bark())
print(tom.sleep())
print(tom.meow())

Dog and Cat have no __init__, eat or sleep of their own, yet they work, because they inherited them from Animal. Each child then added one new method.

Inheritance only goes down, from parent to child. A cat cannot bark, and a plain Animal cannot meow:

Try it yourselfPython
class Animal:
    def __init__(self, name):
        self.name = name


class Dog(Animal):
    def bark(self):
        return f"{self.name} says Woof!"


class Cat(Animal):
    pass


tom = Cat("Tom")
print(hasattr(tom, "bark"))
print(hasattr(Dog("Rex"), "bark"))

hasattr(obj, "name") checks whether an object has an attribute or method with that name.

How Python finds a method

When you call rex.eat(), Python searches in order:

  1. The object itself.
  2. Its class, Dog. Is there an eat here? No.
  3. The parent class, Animal. Yes, use this one.

This is the same lookup you saw with class attributes, just extended upwards through the family.

The "is-a" test

Use inheritance only when this sentence makes sense. "A dog is an animal" is true, so Dog(Animal) is a good design. "A car is an engine" is false, so a car should not inherit from an engine. (You will learn the right tool for that, composition, in a later lesson.)

Checking types: isinstance() and issubclass()

Try it yourselfPython
class Animal:
    pass


class Dog(Animal):
    pass


class Cat(Animal):
    pass


rex = Dog()

print(isinstance(rex, Dog))
print(isinstance(rex, Animal))
print(isinstance(rex, Cat))

print(issubclass(Dog, Animal))
print(issubclass(Animal, Dog))

rex is a Dog and also an Animal, because every dog is an animal. It is not a Cat.

Inheritance chains

A child class can itself be a parent. Each level gets everything from the levels above it.

Try it yourselfPython
class Vehicle:
    def __init__(self, brand):
        self.brand = brand

    def start(self):
        return f"{self.brand} is starting"


class Car(Vehicle):
    def drive(self):
        return f"{self.brand} is driving on the road"


class ElectricCar(Car):
    def charge(self):
        return f"{self.brand} is charging"


ev = ElectricCar("Tata")
print(ev.start())
print(ev.drive())
print(ev.charge())
print(isinstance(ev, Vehicle))

Class methods and inheritance

Remember cls from the Class Methods lesson? Because it holds whichever class the method was called on, an alternative constructor in the parent automatically builds the right child.

Try it yourselfPython
class Animal:
    def __init__(self, name):
        self.name = name

    @classmethod
    def from_text(cls, text):
        return cls(text.strip().title())


class Dog(Animal):
    pass


pet = Dog.from_text("  rex ")
print(type(pet).__name__, pet.name)

Dog.from_text(...) runs the parent's method with cls set to Dog, so you get a Dog, not an Animal.

Common mistakes

Practice exercise

Write a parent class once, then build two child classes that share it and add their own abilities.

Your solutionPython
# 1. Write a parent class Vehicle with __init__(self, name, wheels)
#    and a method describe(self) that returns e.g. "Bike has 2 wheels"
# 2. Write a child class Bike(Vehicle) with a method ring(self) that returns "Ring ring!"
# 3. Write a child class Truck(Vehicle) with a method load(self, tonnes)
#    that returns e.g. "Truck carries 8 tonnes"


bike = Bike("Bike", 2)
truck = Truck("Truck", 6)
print(bike.describe())
print(bike.ring())
print(truck.describe())
print(truck.load(8))
print(isinstance(truck, Vehicle))

# Output must be exactly:
# Bike has 2 wheels
# Ring ring!
# Truck has 6 wheels
# Truck carries 8 tonnes
# True
Knowledge check

class Dog(Animal) is defined, and rex = Dog(). What does isinstance(rex, Animal) return?

Summary

  • Inheritance builds a child class from a parent class: class Child(Parent):.
  • The child gets all of the parent's attributes and methods, and can add its own.
  • Python looks for a method on the object, then its class, then each parent in turn.
  • Use inheritance only for a true is-a relationship.
  • isinstance() checks an object's type, counting parents. issubclass() checks two classes.

Next: changing an inherited method, and calling the parent's version with super().

Finished reading? Tick it off to track your progress.