Dataclass Inheritance in Python

Level 5257 keystrokes

This shows dataclass inheritance with mutable default values. field(default_factory=list) creates a new list for each instance.

Python code

# Import dataclass and field from dataclasses
1from dataclasses import dataclass, field
2
# Define base dataclass for animals
3@dataclass
# Animal class with name and age
4class Animal:
# Required name field
5 name: str
# Optional age with default 0
6 age: int = 0
7
# Define derived dataclass for dogs
8@dataclass
# Dog inherits from Animal
9class Dog(Animal):
# Optional breed with default
10 breed: str = "Unknown"
# Mutable default via field(default_factory=...)
11 tricks: list = field(default_factory=list)
12
# Create dog instance with positional args
13dog = Dog("Buddy", 3, "Labrador")
# Add a trick to the dog's tricks list
14dog.tricks.append("sit")
# Print the dog object
15print(dog)

Output

Dog(name='Buddy', age=3, breed='Labrador', tricks=['sit'])
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 8
  • :× 6
  • (× 5
  • )× 5
  • =× 5
  • ,× 3
  • .× 2
  • @× 2
  • _× 1

More Python examples at level 5

← Python typing practice