← All lessons
Python advanced · Lesson 3 of 11

Inheritance and composition

Inheritance lets a new class start from an existing one. Write the parent in brackets: class Duck(Bird):. The child (or subclass) gets all of the parent's methods and attributes, and can add its own or replace them. Replacing a parent's method is called overriding it.

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

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

    def intro(self):
        return f"{self.name} says {self.speak()}"

class Duck(Bird):
    def speak(self):
        return "Quack"

class Owl(Bird):
    def speak(self):
        return "Hoo"

for b in [Duck("Dot"), Owl("Ollie"), Bird("Bea")]:
    print(b.intro())
Prints
Dot says Quack
Ollie says Hoo
Bea says ...

intro() is written once, in Bird, and calls self.speak(). Python looks the method up on the actual object, so each bird speaks its own way. Code that works with any object that has the right methods, whatever its class, is called polymorphic.

super() reaches the parent's version of a method. It's used most in __init__, so a child can set up its extra attributes and still let the parent do its part.

class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

class Savings(Account):
    def __init__(self, owner, balance=0, rate=0.03):
        super().__init__(owner, balance)
        self.rate = rate

    def add_interest(self):
        self.balance += round(self.balance * self.rate, 2)

s = Savings("Ana", 200)
s.add_interest()
print(s.owner, s.balance)
Prints
Ana 206.0

isinstance(obj, Class) asks whether an object is an instance of a class or any subclass of it, and issubclass() asks the same about classes. Every class ultimately inherits from object.

class Bird: pass
class Duck(Bird): pass
class Owl(Bird): pass

d = Duck()
print(isinstance(d, Duck), isinstance(d, Bird), isinstance(d, Owl))
Prints
True True False

Inheritance is the right tool when the child really is a kind of the parent (a Savings account is an Account). When one thing merely uses another, composition is usually better: give the object an attribute holding the other object. A Car has an Engine; it isn't one. Deep inheritance trees are hard to follow, so experienced Python code keeps them shallow and composes freely.

class Engine:
    def start(self):
        return "vroom"

class Car:
    def __init__(self):
        self.engine = Engine()

    def drive(self):
        return self.engine.start() + ", off we go"

print(Car().drive())
Prints
vroom, off we go

Python also offers abstract base classes (from abc import ABC, abstractmethod) for a parent that only defines which methods its children must have. Python's own idea of duck typing ("if it walks like a duck and quacks like a duck") means you often don't need them: any object with the right methods will do.

Practice

What does this print?

class A:
    def hello(self):
        return "A"

class B(A):
    pass

print(B().hello())
More info

Quick reference

class Child(Parent):Inheritance: Child gets Parent's methods and attributes.
overrideDefine a method with the same name in the child to replace it.
super().method(...)Call the parent's version.
isinstance(obj, C)Is obj a C or a subclass of C?
compositionHold another object as an attribute (has-a) instead of inheriting (is-a).
duck typingAny object with the right methods works, whatever its class.

Related courses