Syllabus Lesson 51 of 239 · Object-Oriented Python
Object-Oriented Python

Inheritance and super()

Inheritance lets one class build on another. The new class (the subclass) gets all the attributes and methods of the original (the parent, or base class) for free, and can add or change behaviour.

You name the parent in parentheses after the subclass name:

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

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

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

rex = Dog("Rex")
print(rex.name)      # Rex   (inherited __init__)
print(rex.speak())   # Woof  (overridden method)

Dog did not define __init__, so it reused the one from Animal. It did define speak, which overrides the parent version.

Calling the parent with super()

Sometimes you want to extend the parent rather than fully replace it. super() gives you the parent so you can call its version, then add more. This is common in __init__:

class Cat(Animal):
    def __init__(self, name, indoor):
        super().__init__(name)   # let Animal set self.name
        self.indoor = indoor     # then add our own

c = Cat("Milo", True)
print(c.name, c.indoor)   # Milo True

You can check the family relationship with isinstance: a Cat is also an Animal.

print(isinstance(c, Animal))   # True
Your turn

Start from a parent class Shape with a method area(self) that returns 0. Define a subclass Square whose __init__ takes side, calls super().__init__(), stores self.side, and overrides area to return side * side. Create sq = Square(4).

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output