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.
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.
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
| Ask | Use |
|---|---|
| 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.
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.
