Dataclass and inheritance

Less boilerplate and shared behaviour of classes.

Classes that mostly hold data are easier to declare with dataclass. The decorator writes __init__, __repr__ and __eq__ from the list of fields for you:

from dataclasses import dataclass, field

@dataclass
class Order:
    number: int
    items: list = field(default_factory=list)
    paid: bool = False

print(Order(1))   # Order(number=1, items=[], paid=False)

The type annotations (: int) are required here: dataclass learns the fields from them. Python does not check them at run time, but editors and checking tools use them.

A mutable default value cannot be written as items: list = []; dataclass raises an error. The reason is the same as with function parameters: one list for all objects. field(default_factory=list) creates a new list for each object. With @dataclass(frozen=True) the object becomes immutable and can be put into sets.

Inheritance lets you take a ready class and extend it. A child class gets all of its parent's methods and can override the ones it needs:

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

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

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

class Puppy(Dog):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age

print(Puppy("Rex", 1).speak())   # Woof

Dog overrides speak, and Puppy gets it from Dog. super().__init__(name) calls the parent's constructor so its code is not repeated. isinstance(Puppy("Rex", 1), Dog) returns True: a puppy is a dog too. Inheritance fits when the "is a" relationship really holds. If one object simply uses another, it is better to keep it in an attribute. This technique is called composition.

Practice

  1. An automatic repr

    What does the program print?

    from dataclasses import dataclass
    
    @dataclass
    class P:
        x: int
        y: int = 0
    
    print(P(1))
    
  2. A list in a dataclass

    What is the right way to give a list field an empty default value in a dataclass?

    • items: list = field(default_factory=list)
    • items: list = []
    • items: list = list
    • items = None: list
  3. Shapes

    Declare three classes. In Shape the method area() returns 0. Rect(Shape) takes w and h and computes the area. Square(Rect) takes a single side and calls the parent's constructor through super().