Show contents
Chapter 2 of 6 · 20 min
Dataclasses and inheritance
By the end of this chapter, you'll be able to
- Declare a data class with @dataclass
- Give a mutable default value with field(default_factory=...)
- Create a subclass that inherits from a class and redefines a method
- Call the parent constructor with super()
Dataclasses: data classes in one line
The @dataclass decorator, placed above the class, reads the annotated attributes (name: str) and generates __init__, a readable display and the == comparison for you:
from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
tags: list[str] = field(default_factory=list)
tea = Product("Green tea", 4.0)
other = Product("Green tea", 4.0)
print(tea)
print(tea == other)
tea.tags.append("organic")
print(tea.tags, other.tags)
Product(name='Green tea', price=4.0, tags=[])
True
['organic'] []
name: stris a type annotation: it documents the expected type. Python doesn't check it at run time, but your editor and analysis tools use it.==compares the attributes' values: two identical products are equal, even though they're two separate objects.field(default_factory=list)creates a new empty list for each product. We'll come back to this in the pitfall below.@dataclass(frozen=True)makes objects unchangeable: any assignment then raises an error. It's useful for values that mustn't change, such as a currency.
Inheritance: a family of classes
A subclass inherits all the attributes and methods of its parent class. It can add some, or redefine a method to adapt it:
import math
class Shape:
def __init__(self, name):
self.name = name
def area(self):
raise NotImplementedError("each shape computes its own area")
def describe(self):
return f"{self.name}: {self.area():.2f} m²"
class Rectangle(Shape):
def __init__(self, width, height):
super().__init__("Rectangle")
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle")
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
garden = [Rectangle(4, 2.5), Circle(1.5), Rectangle(3, 3)]
for shape in garden:
print(shape.describe())
print(f"Total area: {sum(s.area() for s in garden):.2f} m²")
print(isinstance(garden[1], Shape), isinstance(garden[1], Rectangle))
Rectangle: 10.00 m²
Circle: 7.07 m²
Rectangle: 9.00 m²
Total area: 26.07 m²
True False
class Rectangle(Shape):declares thatRectangleinherits fromShape. It getsdescribe()for free.super().__init__("Rectangle")calls the parent's constructor so that it does its part (storing the name).describe()is written only once, inShape, and callsself.area(). Python automatically picks the right version for the object: this is polymorphism.isinstance(obj, Class)tests whether an object belongs to a class or one of its subclasses.:.2fin an f-string displays a number with two decimals.
The loop never needs to test the shape's type: each object knows how to compute its own area.
Text description of the animation
- garden contains a Rectangle, a Circle and another Rectangle. None of them defines describe: they all inherit it from Shape.
- describe calls self.area(). self is a Rectangle: Python uses Rectangle's version, 4 × 2.5.
- Same line of code, different object: this time self is a Circle, and it's π × 1.5² that gets computed.
- The loop never needs to test the shape's type: each object knows how to compute its own area.
Inherit or not? Only inherit if the sentence "an X is a Y" is true: a circle is a shape. If it's rather "an X has a Y" (a shop has a stock), put an object in an attribute: that's composition, more flexible and more common.
Your turn
Worked exercise
Worked exercise: the triangle
Add a class Triangle(base, height) to the family of shapes, whose area is base × height ÷ 2. Then write a function largest(shapes) that returns the shape with the largest area. With a 4 × 2.5 rectangle, a circle of radius 1.5 and a triangle with base 6 and height 4, the program displays Triangle 12.0.
Hint 1
Triangle inherits from Shape, calls super().__init__("Triangle") and only redefines area.Hint 2
max(shapes, key=lambda s: s.area()) looks for the maximum based on each shape's area.Show the solution and common mistakes
import math
class Shape:
def __init__(self, name):
self.name = name
def area(self):
raise NotImplementedError
class Rectangle(Shape):
def __init__(self, width, height):
super().__init__("Rectangle")
self.width, self.height = width, height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle")
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
class Triangle(Shape):
def __init__(self, base, height):
super().__init__("Triangle")
self.base, self.height = base, height
def area(self):
return self.base * self.height / 2
def largest(shapes):
return max(shapes, key=lambda s: s.area())
shapes = [Rectangle(4, 2.5), Circle(1.5), Triangle(6, 4)]
big = largest(shapes)
print(big.name, big.area())
Triangle 12.0
Common mistakes:
- Forgetting
super().__init__(...): thenameattribute doesn't exist, andbig.nameraises anAttributeError. - Writing
max(shapes)withoutkey: Python doesn't know how to compare two shapes and raises aTypeError.
Summary
- 1@dataclass generates __init__, the display and == from the annotated attributes.
- 2field(default_factory=list) gives each object its own list.
- 3A subclass inherits the parent's methods and can redefine them; super() calls the parent.
- 4Polymorphism: the same call runs each object's own version.
- 5Only inherit if "X is a Y"; otherwise, prefer composition.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.