Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Object-Oriented Python

Python Composition, Abstract Classes and Dataclasses

When an object should hold another object instead of inheriting, how an abstract class refuses to be created until every rule is filled in, and how @dataclass writes __init__, __repr__ and __eq__ for you, with real outputs and errors.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Python

What you will learn

  • Choose between inheritance (is a) and composition (has a), and tell composition from aggregation
  • Write an abstract class with ABC and @abstractmethod and read the errors it raises
  • Replace a boilerplate class with @dataclass and use field(default_factory=list)
  • Use frozen, order, field(init=False) and __post_init__ on a dataclass

Before you start

  • Python inheritance and super()
  • Decorators and the @ sign
  • Type hints

So far, when one class needed what another class had, we reached for inheritance. That isn't the only way classes work together, and writing every class by hand isn't the only way to build them. This article covers three tools that shape how you build classes: composition, abstract classes and dataclasses.

Is a, or has a?

Start with a car. A car is a vehicle. That's an "is a" relationship, and that's inheritance: Car would inherit from Vehicle. A car also has an engine, but a car isn't an engine. The engine is a part sitting inside it. That's a "has a" relationship, and that's composition: one object holds another object as an attribute.

Before you inherit, say the sentence out loud. If "is a" sounds wrong and "has a" sounds right, use composition.

Inheritance: Car is a Vehicle, drawn as an arrow up to the parent. Composition: Computer has a Chip, drawn as the chip object held inside the computer's cpu attribute. Inheritance: is a Vehicle Car(Vehicle) Composition: has a Computer self.cpu = Chip Intel i9
Inheritance points up to a parent. Composition holds a whole object inside an attribute.

Composition: an object inside an object

class Chip:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model


class Computer:
    def __init__(self, cpu, ram_gb, storage_gb):
        self.cpu = cpu
        self.ram_gb = ram_gb
        self.storage_gb = storage_gb

    def specs(self):
        return (f"{self.cpu.brand} {self.cpu.model}, "
                f"{self.ram_gb} GB RAM, "
                f"{self.storage_gb} GB disk")


chip = Chip("Intel", "i9")
pc = Computer(chip, 32, 1000)

print(pc.specs())
print(pc.cpu is chip)
print(isinstance(pc, Chip))
Intel i9, 32 GB RAM, 1000 GB disk
True
False

Computer doesn't inherit from Chip. self.cpu = cpu looks like a normal variable, but it holds a whole object, and specs reaches through it with self.cpu.brand. pc.cpu is chip is True, so it's the very same object, not a copy. And isinstance(pc, Chip) is False: a computer has a chip, but it isn't one.

Who owns the part: composition and aggregation

People split "has a" into two kinds. The difference is who owns the part.

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


class House:
    def __init__(self, room_names):
        self.rooms = [Room(n) for n in room_names]

    def describe(self):
        names = [r.name for r in self.rooms]
        return f"House with {len(names)} rooms: {names}"


home = House(["kitchen", "bedroom", "bath"])
print(home.describe())
House with 3 rooms: ['kitchen', 'bedroom', 'bath']

We pass in only names. The house makes each Room itself, so the rooms exist only inside it. That's strong ownership, composition in its strict sense. Now the other kind:

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


class Company:
    def __init__(self, name):
        self.name = name
        self.staff = []

    def hire(self, employee):
        self.staff.append(employee)


alice = Employee("Alice")
tech = Company("TechCo")
tech.hire(alice)

print(tech.staff[0].name)
tech.staff.clear()
print(len(tech.staff), alice.name)
Alice
0 Alice

Alice is created first, outside any company. hire adds a reference to her, not a new Alice. When we clear the staff list, the count drops to 0 but alice.name still works. This is aggregation, or loose ownership: the company uses Alice, but she doesn't depend on it. In everyday talk, people often call both kinds composition.

Abstract classes: a form with required boxes

Think of an application form with two required boxes. The blank form can't be submitted; it's only a template. Fill in one box and leave the other empty, and the counter hands it back. Fill in both and it goes through. An abstract class is that form. It lists what every child must fill in, and Python is the counter that checks.

from abc import ABC, abstractmethod


class Shape(ABC):
    @abstractmethod
    def area(self):
        ...

    @abstractmethod
    def perimeter(self):
        ...


class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

    def perimeter(self):
        return 4 * self.side


sq = Square(3)
print(sq.area(), sq.perimeter())
print(isinstance(sq, Shape))
9 12
True

Shape inherits from ABC, which makes it abstract. @abstractmethod is a ready-made decorator that marks a method as required; the three dots mean there's no body, only the promise. Square writes both, so it works.

The two errors you'll see

Try to create the form itself:

from abc import ABC, abstractmethod


class Shape(ABC):
    @abstractmethod
    def area(self):
        ...


s = Shape()
print("never reached")
Traceback (most recent call last):
  File "S03L06_Composition\shape_direct.py", line 10, in <module>
    s = Shape()
TypeError: Can't instantiate abstract class Shape without an implementation for abstract method 'area'

Python checks the class before it builds anything, so the object never gets made and the print never runs. Now a child that forgets one method. Circle writes area but not perimeter:

from abc import ABC, abstractmethod


class Shape(ABC):
    @abstractmethod
    def area(self):
        ...

    @abstractmethod
    def perimeter(self):
        ...


class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius ** 2


c = Circle(2)
print(c.area())
Traceback (most recent call last):
  File "S03L06_Composition\shape_incomplete.py", line 22, in <module>
    c = Circle(2)
TypeError: Can't instantiate abstract class Circle without an implementation for abstract method 'perimeter'

It fails the moment we create the object, and the message names the missing piece. That's the benefit: a missing method shows up straight away instead of crashing later when somebody finally calls it.

Required properties

from abc import ABC, abstractmethod


class PaymentProcessor(ABC):
    @property
    @abstractmethod
    def provider_name(self):
        ...

    @abstractmethod
    def process_payment(self, amount):
        ...

    @abstractmethod
    def refund(self, amount):
        ...


class CreditCard(PaymentProcessor):
    @property
    def provider_name(self):
        return "Visa"

    def process_payment(self, amount):
        return f"Paid {amount} with {self.provider_name}"

    def refund(self, amount):
        return f"Refunded {amount}"


cc = CreditCard()
print(cc.provider_name)
print(cc.process_payment(50))
print(cc.refund(20))
Visa
Paid 50 with Visa
Refunded 20

Stacking @property and @abstractmethod means every child must supply provider_name as a property. The caller doesn't care which processor it has, because every child has the same three things.

Dataclasses: skip the boilerplate

Here's a class that only holds two numbers, written by hand:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"

    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)


p = Point(1.5, 2.0)
q = Point(1.5, 2.0)
print(p)
print(p == q)
Point(x=1.5, y=2.0)
True

Ten lines for two numbers, and every name shows up three times. Now the same Point as a dataclass:

from dataclasses import dataclass


@dataclass
class Point:
    x: float
    y: float


p = Point(1.5, 2.0)
q = Point(1.5, 2.0)
print(p)
print(p == q)
print(p is q)
print(p.x, p.y)
Point(x=1.5, y=2.0)
True
False
1.5 2.0

x: float and y: float are type hints that give each field a name and an expected type. The decorator reads the fields from top to bottom and writes the same __init__ we typed by hand, plus __repr__ and __eq__. p is q is still False: equal in value, but two objects. A dataclass is still a normal class.

A list as a default

from dataclasses import dataclass

try:
    @dataclass
    class Student:
        name: str
        grades: list = []
except ValueError as e:
    print(type(e).__name__)
    print(e)
ValueError
mutable default <class 'list'> for field grades is not allowed: use default_factory

A default like [] is made once and sits on the class, so every student would share that one list. Add a grade for Alice and Bob would get it too. The dataclass stops this when the class is defined, and the message tells you the fix:

from dataclasses import dataclass, field


@dataclass
class Student:
    name: str
    age: int
    grades: list = field(default_factory=list)

    @property
    def average(self):
        return sum(self.grades) / len(self.grades)


alice = Student("Alice", 20, [80, 90, 100])
bob = Student("Bob", 21)
bob.grades.append(70)

print(alice)
print(alice.average)
print(bob)
Student(name='Alice', age=20, grades=[80, 90, 100])
90.0
Student(name='Bob', age=21, grades=[70])

field() sets options for one field, and default_factory=list means "call list each time an object is made". Bob gets a fresh empty list of his own. You can still add properties too.

Dataclass options: frozen, order, init=False

from dataclasses import dataclass


@dataclass(frozen=True)
class Config:
    host: str
    port: int


cfg = Config("localhost", 8000)
print(cfg)
cfg.port = 9000
print("never reached")
Config(host='localhost', port=8000)
Traceback (most recent call last):
  File "S03L06_Composition\frozen_config.py", line 12, in <module>
    cfg.port = 9000
    ^^^^^^^^
  File "<string>", line 16, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'port'

frozen=True means once the values are set, they stay. It suits settings that shouldn't change while the program runs.

from dataclasses import dataclass


@dataclass(order=True)
class Version:
    major: int
    minor: int


a = Version(1, 4)
b = Version(2, 0)
c = Version(1, 9)

print(a < b)
print(a < c)
print(sorted([b, c, a]))
True
True
[Version(major=1, minor=4), Version(major=1, minor=9), Version(major=2, minor=0)]

order=True writes the comparison methods. It compares field by field, in the order you listed them: a < c ties on major, so minor decides, 4 against 9.

from dataclasses import dataclass, field


@dataclass
class Product:
    name: str
    price: float
    quantity: int
    total: float = field(init=False)

    def __post_init__(self):
        self.total = self.price * self.quantity


pen = Product("Pen", 2.5, 4)
print(pen)
bad = Product("Pen", 2.5, 4, 99)
Product(name='Pen', price=2.5, quantity=4, total=10.0)
Traceback (most recent call last):
  File "S03L06_Composition\product_total.py", line 17, in <module>
    bad = Product("Pen", 2.5, 4, 99)
TypeError: Product.__init__() takes 4 positional arguments but 5 were given

field(init=False) keeps total out of the generated __init__, and __post_init__ runs right after __init__ to work it out: 2.5 times 4 is 10.0. Passing a total anyway fails. The "4" counts self, so there's no slot for it. Nobody can pass in a wrong total.

When to use what

AskUse
Is it truly a kind of the parent? (car, vehicle)inheritance
Does it have a part? (computer, chip)composition; a good default when unsure
Must every child give the same methods?abstract class
Does the class mostly hold data?dataclass

Later you'll meet Pydantic, which looks like a dataclass and also checks the values; see structured LLM output with Pydantic. AI tools generate all of this well. What you need is to read the code and know which tool it picked and why.

Try it yourself

Add a Rectangle to the abstract Shape file, leave out perimeter and read the error, then add it. Or prompt an AI tool to write it, then read every line it gives you.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 23 of 48

Previous
Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
Next post
Python OOP Practice: Design a Bank, an Employee System and a Library

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Python Class Methods, Static Methods and Properties: What Each One Receives

Instance methods get self, class methods get cls, static methods get nothing. Then properties, setters and deleters, with small runnable files and their real output.

Python Classes and Objects: __init__, self and PEP 8 Names

A class is the blueprint and an object is what you build from it. Car, Student, Dog, Circle and BankAccount show what __init__ and self really do, how attribute lookup works, the missing self error, and PEP 8 names.

Python Inheritance and Polymorphism: super(), Overriding and Duck Typing

A child class gets everything from its parent, Python walks up and stops at the first match, and super() reaches the parent. Then polymorphism: one call, a different method for each object, with Animal, Employee and Shape examples and their real output.

Python Multiple Inheritance, the MRO and Mixins

A class can have two parents or a whole chain of them, and one list puts them in order: the MRO. Read it, watch Python walk it, see super() follow it, and build JsonMixin and LogMixin for a User class.

On this page

  • Is a, or has a?
  • Composition: an object inside an object
  • Who owns the part: composition and aggregation
  • Abstract classes: a form with required boxes
  • The two errors you'll see
  • Required properties
  • Dataclasses: skip the boilerplate
  • A list as a default
  • Dataclass options: frozen, order, init=False
  • When to use what
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.