Intermediate Python · Lesson 10 of 14

Inheritance and super()

Build new classes on top of existing ones, override methods, reuse parent code with super(), and treat related objects the same way.

About 16 minutes · code runs in your browser, nothing to install

Inheritance lets a new class start from an existing one. The new class (the child or subclass) gets every method and attribute of the parent, and can add new ones or replace some. Write the parent's name in brackets after the class name.

Pythoneditable
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def describe(self):
        return f"{self.name} earns {self.salary}"

class Manager(Employee):
    def approve(self, request):
        return f"{self.name} approved {request}"

m = Manager("Ines", 5200)
print(m.describe())
print(m.approve("a day off"))
Output
Ines earns 5200
Ines approved a day off

Manager has no __init__ or describe of its own; it uses Employee's.

Adding to __init__ with super()

When a child needs extra attributes, it writes its own __init__. super() calls the parent's version, so the shared set-up is not copied.

Pythoneditable
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def yearly_pay(self):
        return self.salary * 12

class Manager(Employee):
    def __init__(self, name, salary, team):
        super().__init__(name, salary)
        self.team = team

    def yearly_pay(self):
        return super().yearly_pay() + 1000 * len(self.team)

m = Manager("Ines", 5200, ["Ali", "Bea"])
print(m.name, m.team)
print(m.yearly_pay())
Output
Ines ['Ali', 'Bea']
64400

yearly_pay is overridden: the manager's version starts from the parent's result and adds a bonus per team member.

Overriding and polymorphism

A child can override a method by defining one with the same name. Code that loops over a mix of objects can then call the same method on each and get the right behaviour for each type. This is called polymorphism.

Pythoneditable
class Payment:
    def __init__(self, amount):
        self.amount = amount

    def fee(self):
        raise NotImplementedError("each payment type sets its own fee")

class Card(Payment):
    def fee(self):
        return round(self.amount * 0.015, 2)

class BankTransfer(Payment):
    def fee(self):
        return 0.5

class Cash(Payment):
    def fee(self):
        return 0

for p in [Card(80), BankTransfer(80), Cash(80)]:
    print(type(p).__name__, p.fee())

try:
    Payment(10).fee()
except NotImplementedError as e:
    print("Error:", e)
Output
Card 1.2
BankTransfer 0.5
Cash 0
Error: each payment type sets its own fee

Checking types

isinstance() answers True for the object's own class and every parent class. issubclass asks the same about two classes.

Pythoneditable
class Vehicle:
    pass

class Car(Vehicle):
    pass

class Bike(Vehicle):
    pass

c = Car()
print(isinstance(c, Car), isinstance(c, Vehicle), isinstance(c, Bike))
print(issubclass(Bike, Vehicle))
print([cls.__name__ for cls in Car.__mro__])
Output
True True False
True
['Car', 'Vehicle', 'object']

__mro__ (method resolution order) is the list of classes Python searches, in order, when it looks up a method. Every class ends with object.

Tip: Use inheritance for a real "is a" relationship: a manager is an employee. If one thing just has another (a shop has a basket), store it as an attribute instead.

✎ Exercise

Write a parent class Shape with a name attribute and a describe() method that returns "<name> with area <area>", using self.area() rounded to 2 places. Then write Circle(radius) and Square(side) that call super().__init__ with their name and define area().

Hint: describe() lives only in Shape and calls self.area(); Python finds the child's area() at run time.

Your codewrite your answer, then Run
import math

class Shape:
    # your code here
    pass

for shape in [Circle(1.5), Square(4)]:
    print(shape.describe())

Expected output:

Circle with area 7.07
Square with area 16
Show a solution
Solutioneditable
import math

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

    def area(self):
        raise NotImplementedError

    def describe(self):
        return f"{self.name} with area {round(self.area(), 2)}"

class Circle(Shape):
    def __init__(self, radius):
        super().__init__("Circle")
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2

class Square(Shape):
    def __init__(self, side):
        super().__init__("Square")
        self.side = side

    def area(self):
        return self.side ** 2

for shape in [Circle(1.5), Square(4)]:
    print(shape.describe())
Output
Circle with area 7.07
Square with area 16

Check yourself

1. What does super().__init__(name) do inside a child's __init__?

2. If Car inherits from Vehicle, what is isinstance(Car(), Vehicle)?

3. A child class defines a method with the same name as one in the parent. What is this called?

Spotted a mistake on this page? Tell us