Inheritance, composition and dataclasses
Build on existing classes with inheritance and super(), organise objects with composition, and write simple data classes with @dataclass.
In this lesson you will
- Create subclasses and override methods
- Use super() and isinstance
- Choose composition over deep inheritance
- Write dataclasses for simple records
About 22 minutes
Building on what already exists
A phone company sells a basic phone. Later it makes a smartphone: it does everything the basic phone does, plus apps and a camera. The engineers do not redraw the whole phone from scratch; they start from the basic design and add to it. Programmers do the same with inheritance: a new class receives everything from an existing class and adds or changes what it needs. This lesson also introduces dataclasses, a shortcut that removes most of the boring code from simple classes.
Inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
def describe(self):
return f"I am {self.name}"
class Dog(Animal): # Dog inherits from Animal
def speak(self): # override the parent's version
return f"{self.name} barks"
class Cat(Animal):
def speak(self):
return f"{self.name} meows"
for pet in [Dog("Rex"), Cat("Tom"), Animal("Thing")]:
print(pet.speak())
print(pet.describe())
Rex barks
I am Rex
Tom meows
I am Tom
Thing makes a sound
I am Thing
class Dog(Animal) says: Dog is a kind of Animal. It automatically has __init__ and describe. It replaces (overrides) speak with its own version. The loop treats all three objects alike, and each responds in its own way. That idea is called polymorphism: “many forms”.
Extending the parent with super()
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def annual(self):
return self.salary * 12
class Manager(Employee):
def __init__(self, name, salary, team):
super().__init__(name, salary) # let the parent set up name and salary
self.team = team
def annual(self):
return super().annual() + 50000 # reuse the parent's calculation, then add a bonus
m = Manager("Sara", 100000, ["Ali", "Mina"])
print(m.name, m.team)
print(m.annual())
Sara ['Ali', 'Mina']
1250000
isinstance and issubclass
class Shape: pass
class Circle(Shape): pass
c = Circle()
print(isinstance(c, Circle))
print(isinstance(c, Shape)) # a Circle is also a Shape
print(issubclass(Circle, Shape))
print(type(c).__name__)
True
True
True
Circle
Abstract ideas: forcing children to fill in a method
from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def area(self):
"""Every shape must say how to compute its area."""
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return math.pi * self.r ** 2
for s in [Square(3), Circle(2)]:
print(type(s).__name__, round(s.area(), 2))
try:
Shape()
except TypeError as e:
print("Cannot create a Shape directly")
Square 9
Circle 12.57
Cannot create a Shape directly
Composition: has-a instead of is-a
class Engine:
def start(self):
return "Engine running"
class Car:
def __init__(self):
self.engine = Engine() # a Car HAS an Engine
def start(self):
return "Car: " + self.engine.start()
print(Car().start())
Car: Engine running
Long chains of inheritance (A inherits B inherits C inherits D) become hard to follow. If you can say “a Car has an Engine”, use composition. Use inheritance only when you can honestly say “a Dog is an Animal”.
Dataclasses: classes without the boilerplate
Many classes just hold data. Writing __init__, __repr__ and __eq__ for each is tedious. The dataclasses module generates them from a short list of fields.
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
in_stock: bool = True
a = Product("Notebook", 120.5)
b = Product("Pen", 45, False)
print(a)
print(b.in_stock)
print(a == Product("Notebook", 120.5))
a.price = 130
print(a.price)
Product(name='Notebook', price=120.5, in_stock=True)
False
True
130
Each line like price: float declares a field with a type hint. Python does not enforce the hint, but tools and other programmers use it, and the dataclass uses it to build the constructor. Fields with a value, such as in_stock: bool = True, are optional.
from dataclasses import dataclass, field, asdict
@dataclass(order=True)
class Task:
priority: int
title: str = field(compare=False)
tags: list = field(default_factory=list, compare=False)
tasks = [Task(3, "Relax"), Task(1, "Study"), Task(2, "Cook", ["home"])]
for t in sorted(tasks):
print(t.priority, t.title)
print(asdict(tasks[2]))
1 Study
2 Cook
3 Relax
{'priority': 2, 'title': 'Cook', 'tags': ['home']}
order=Truelets you sort and compare the objects.field(default_factory=list)gives every object its own new list (a plain[]default is a trap: it would be shared).asdict()turns the object into a dictionary, handy for saving as JSON.@dataclass(frozen=True)makes the object unchangeable.
Using a mutable default such as tags: list = []. Python refuses it in dataclasses, and in plain functions the same mistake def add(item, bag=[]) shares one list between every call. Use None or default_factory.
Putting it together: a small inventory
from dataclasses import dataclass
@dataclass
class Item:
name: str
price: float
quantity: int = 0
def total(self):
return self.price * self.quantity
class Inventory:
def __init__(self):
self.items = {}
def add(self, item):
if item.name in self.items:
self.items[item.name].quantity += item.quantity
else:
self.items[item.name] = item
def value(self):
return sum(i.total() for i in self.items.values())
def report(self):
for item in sorted(self.items.values(), key=lambda i: i.name):
print(f"{item.name:<10} {item.quantity:>3} x {item.price:>7.2f} = {item.total():>9.2f}")
print(f"{'TOTAL':<10} {'':>14} {self.value():>9.2f}")
shop = Inventory()
shop.add(Item("Notebook", 120, 10))
shop.add(Item("Pen", 45.5, 40))
shop.add(Item("Notebook", 120, 5))
shop.report()
Notebook 15 x 120.00 = 1800.00
Pen 40 x 45.50 = 1820.00
TOTAL 3620.00
Look at how the two kinds of class work together. Item is a simple record, so a dataclass suits it. Inventory has behaviour and rules, so it is a normal class. Choosing the lightest tool that fits is a mark of a good programmer.
Create a base class Vehicle with a wheels attribute and a method describe(). Then create Bike and Car as children, passing 2 and 4 wheels, and print describe() for each.
Show one possible answer
class Vehicle:
def __init__(self, name, wheels):
self.name = name
self.wheels = wheels
def describe(self):
return f"{self.name} has {self.wheels} wheels"
class Bike(Vehicle):
def __init__(self):
super().__init__("Bike", 2)
class Car(Vehicle):
def __init__(self):
super().__init__("Car", 4)
for v in (Bike(), Car()):
print(v.describe())
Bike has 2 wheels
Car has 4 wheels
Write a dataclass Book with title, author and pages. Make a list of three books and print the title of the longest one.
Hint: max(…, key=lambda b: b.pages)
Show one possible answer
from dataclasses import dataclass
@dataclass
class Book:
title: str
author: str
pages: int
books = [Book("Python Basics", "Sara", 320), Book("Web Design", "Ali", 410), Book("Data Tips", "Mina", 250)]
longest = max(books, key=lambda b: b.pages)
print(longest.title)
Web Design
Do not build a hierarchy of classes before you need one. Start with plain functions and data, add a class when the code cries out for it, and refactor to inheritance only when you see real duplication.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does class Dog(Animal) mean?
- Dog contains Animal
- Animal inherits from Dog
- Dog inherits from Animal
- Dog is a function
The class in brackets is the parent.
What does super().__init__(...) do?
- Calls the parent class constructor
- Creates a new class
- Deletes the parent
- Prints the class
super() gives access to the parent.
What is overriding?
- Deleting a class
- Replacing a parent’s method in the child
- Importing a module
- Looping
The child defines its own version of the method.
What does @dataclass generate for you?
- A database
- A web page
- A loop
- __init__, __repr__ and __eq__
It writes the repetitive methods from the fields.
When is composition better than inheritance?
- Never
- When the relationship is has-a, such as a Car has an Engine
- Only for numbers
- When you want slower code
Has-a relationships are modelled by containing objects.
Summary
- Subclasses inherit and can override.
- super() reuses the parent’s code.
- Prefer has-a (composition) to deep is-a chains.
- @dataclass removes boilerplate for record classes.
Questions
Can a class inherit from several parents?
Yes, Python supports multiple inheritance, but it is easy to get confused. Prefer composition.
What are type hints for?
They document what a value should be and help editors and tools spot mistakes. Python itself does not enforce them.
Dataclass or normal class?
A dataclass for records that mostly hold data. A normal class when behaviour and rules dominate.
