Learn with diagrams, code, systems and practical examples.
Composition, Inheritance, and Dataclasses
Choose simple object relationships and reduce boilerplate for data-focused types.
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.
Small working example
Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
product = Product("Book", 12.0)
print(product.name) Composition means one object contains or uses another. Inheritance means one class extends another. Dataclasses are convenient when a type mainly stores structured data.
- Composition often keeps relationships flexible.
- Inheritance models an is-a relationship.
- Dataclasses reduce repetitive data-object code.
BookThe example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.
Common beginner mistake
Using deep inheritance trees when simple composition would make dependencies easier to understand.
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.
- Create a dataclass for a User.
- Model a CheckoutService that contains another helper object.