Skip to content

Object-Oriented Python: Inheritance and super()

Beginning of the lesson

Inheritance and super()

Build new classes on top of existing ones instead of starting from scratch

Big idea: Inheritance lets a new class reuse the data and behaviour of an existing class. The existing class is the base (or parent); the new class is the derived class (or child). The child gets everything the parent has, and can add to it or change it. super() is how the child cooperates with the parent instead of quietly replacing it.
By the end of this topic you will be able to:
  • define a derived class with class Child(Parent): and explain the is-a relationship,
  • call the parent's __init__ (and other methods) with super(),
  • override a method and know when to extend it versus replace it,
  • decide between inheritance and composition using is-a versus has-a,
  • read a small class hierarchy and predict which method runs.

1. Base classes and derived classes

You already know how to write a single class with __init__ and methods. Inheritance is what happens when two classes share a lot of behaviour and you do not want to copy it twice. Suppose you are modelling animals. Every animal has a name and can eat; only some can bark. Rather than repeat the name/eat code in Dog, Cat and Bird, you put the shared parts in one base class and let each specific animal derive from it.

The test for inheritance is the is-a relationship: a Dog is an Animal, a SavingsAccount is a BankAccount. If that sentence sounds true, inheritance is a candidate. If instead you would say has-a (a Car has an Engine), that is composition, which we cover in section 6.

class Animal:            # base / parent class
    def __init__(self, name):
        self.name = name

    def eat(self):
        return self.name + " is eating"

class Dog(Animal):      # derived / child class -- Dog IS-A Animal
    def bark(self):
        return "Woof!"

d = Dog("Rex")
print(d.eat())          # inherited from Animal
print(d.bark())         # defined on Dog

Output:

Rex is eating
Woof!

Notice that Dog never defines __init__ or eat, yet d.eat() works. Python did not find eat on Dog, so it looked at the parent Animal and used that. That upward search is the heart of inheritance.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers