Inheritance & Dataclasses in Python

From the Python cheat sheet · Classes & OOP · verified Jul 2026

Inheritance & Dataclasses

Extend classes with inheritance and use dataclasses for data containers.

python
# Inheritance
class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        raise NotImplementedError

class Cat(Animal):
    def speak(self):
        return f"{self.name} says meow!"

# Dataclass (3.7+)
from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float
💡 Use super().__init__() to call the parent class constructor
⚡ Dataclasses auto-generate __init__, __repr__, and __eq__ from type annotations
📌 Use field(default_factory=list) for mutable defaults in dataclasses
🟢 @dataclass(frozen=True) makes instances immutable and hashable
inheritancedataclassesoop

More Python tasks

Back to the full Python cheat sheet