Codiqo

Learn Python · lesson 57 of 60 · about 8 minutes

Inheritance

Build a new class on top of an existing one and reuse everything it can do.

What you'll learn

  • Make a child class from a parent class
  • Use inherited methods and attributes
  • Check types with isinstance

The holiday pot

Sam's bike fund is an Account: it takes deposits, refuses anything that doesn't make sense and keeps a statement. Now Sam wants a second pot, for a £200 holiday, that does all of that and one thing more: it says how much of the goal is saved. Writing Account again would be a waste, so Pot is a child class of it: class Pot(Account): gets deposit, withdraw and statement for free and adds percent(goal). The assistant asks for pounds until done and prints Sam: £60 (+20, +40) and 30% of the £200 holiday saved.

Classes that share

A dog and a cat are both animals: both have a name and both can eat. Instead of writing that code twice, you write it once in an Animal class.

class Dog(Animal): makes Dog a child class of Animal. A Dog gets every method and attribute of Animal for free, and can add its own.

Dog inherits from Animal

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

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

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

rex = Dog("Rex")
rex.eat()
rex.fetch()

Output

Rex is eating
Rex fetches the ball

Is it one of those?

isinstance(rex, Dog) is True, and so is isinstance(rex, Animal), because every Dog is also an Animal. It doesn't work the other way: a plain Animal isn't a Dog, so it has no fetch method.

Checking types

class Animal:
    pass

class Dog(Animal):
    pass

rex = Dog()
blob = Animal()
print(isinstance(rex, Animal))
print(isinstance(blob, Dog))

Output

True
False

What Pot gets for free

Pot has no __init__ of its own, so Pot(name, 0) runs Account's: the pot starts with an owner, a balance of 0 and an empty history. holiday.deposit(20) runs Account's deposit, refusals and all, so a 0 still gets Refused: amount must be more than 0. percent is the only new method: self.balance * 100 // goal is the whole-number percentage, and min(100, ...) stops it going past 100 once the goal is reached.

Tip

The parent class is also called the base class or superclass; the child is the subclass. They all mean the same thing.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.