Technology Composition, Inheritance, and Dataclasses | Python Tutorial

Learn with diagrams, code, systems and practical examples.

</>
TutorialsPythonComposition, Inheritance, and Dataclasses
Object-Oriented Python · Chapter 21

Composition, Inheritance, and Dataclasses

Choose simple object relationships and reduce boilerplate for data-focused types.

Why this matters

Larger programs need ways to model related behavior without producing fragile class hierarchies.

Start with the idea

Composition means one object contains or uses another. Inheritance means one class extends another. Dataclasses are convenient when a type mainly stores structured data.

IdeaUnderstand the purpose
CodeRun the smallest example
PracticeChange it yourself
SubjectVision learning pattern: understand the idea before memorizing syntax.

Small working example

Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.

Python
from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float

product = Product("Book", 12.0)
print(product.name)
Expected output
Book
What to notice

The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.

Common beginner mistake

Mistake

Using deep inheritance trees when simple composition would make dependencies easier to understand.

Better approach

Prefer the simplest relationship that accurately represents the domain.

Quick recap

  • Composition often keeps relationships flexible.
  • Inheritance models an is-a relationship.
  • Dataclasses reduce repetitive data-object code.

Try it yourself

These are deliberately small. If you can complete them without copying the example, you are ready to continue.

  1. Create a dataclass for a User.
  2. Model a CheckoutService that contains another helper object.