Python OOP Composition with Dataclasses: Objects Inside Objects
Composition in Python OOP builds an object from other objects: a dataclass field holds another dataclass, and its methods call that object's methods.
Read Python Dataclasses and Python Dataclass Methods first. This lesson shows how to store one dataclass in another, one object or a list of them, and how the outer object uses their methods.
Store another object
A field's type hint can name another dataclass. The field then holds a whole object of that class.
from dataclasses import dataclass@dataclassclass Battery: capacity: int used: int@dataclassclass Phone: model: str battery: Batteryphone = Phone("Pixel", Battery(4000, 1500))print(phone)print(phone.battery.capacity)This prints Phone(model='Pixel', battery=Battery(capacity=4000, used=1500)), then 4000. The generated display shows the battery inside the phone. phone.battery is the Battery object, so phone.battery.capacity reads one of its fields: each dot steps one object further in.
Use composition when one object has another: a phone has a battery. Inheritance is for "is a kind of": a phone is not a kind of battery.
Delegate to a contained object
A method of the outer object can call a method of the object it holds. This is delegation: Phone asks its battery instead of repeating the battery's calculation.
from dataclasses import dataclass@dataclassclass Battery: capacity: int used: int def left(self): return self.capacity - self.used@dataclassclass Phone: model: str battery: Battery def status(self): return f"{self.model}: {self.battery.left()} mAh left"phone = Phone("Pixel", Battery(4000, 1500))print(phone.status())This prints Pixel: 2500 mAh left. self.battery is the phone's Battery, and .left() runs that battery's own method. If the rule for charge left changes, only Battery changes.
Collections of contained objects
A field can hold a list of objects. The type hint list[Battery] means a list whose items are Battery objects. Pass such a list when you create the object.
from dataclasses import dataclass@dataclassclass Battery: capacity: int used: int def left(self): return self.capacity - self.used@dataclassclass Drawer: batteries: list[Battery]drawer = Drawer([Battery(3000, 500), Battery(2000, 1800)])print(drawer.batteries[0])for battery in drawer.batteries: print(battery.left())This prints Battery(capacity=3000, used=500), then 2500 and 200. drawer.batteries[0] is the first Battery in the list. In the loop, each battery works out its own charge left. Inside a method of Drawer, the same list is self.batteries.
Call the method on an item, not the list
drawer.batteries is the whole list; drawer.batteries[0] is one Battery in it. Only a Battery has left(), so calling it on the list fails.
from dataclasses import dataclass@dataclassclass Battery: capacity: int used: int def left(self): return self.capacity - self.used@dataclassclass Drawer: batteries: list[Battery]drawer = Drawer([Battery(3000, 500)])print(drawer.batteries[0].left())print(drawer.batteries.left()) # this line raises AttributeError: a list has no left()This prints 2500, then stops with AttributeError: 'list' object has no attribute 'left'. Pick an item first, by its index or in a loop.
Note: The outer object holds the same object you passed in, not a copy. Change battery.used later and phone.status() reports the new value. Type hints are not checked at runtime, so Drawer(["AA"]) is accepted and fails only when a method calls left() on the text. self.batteries[0] on an empty list raises IndexError; these examples assume the list has the items they read.
See also: Classes and objects, Methods and self.
Your turn
Give Shelf a field books that holds a list of Book objects, and a method first_label() that returns the first book's label().
Dune (412 pages)
from dataclasses import dataclass@dataclassclass Book: title: str pages: int def label(self): return f"{self.title} ({self.pages} pages)"@dataclassclass Shelf: pass # replace pass with the field books and the method first_label(self)shelf = Shelf([Book("Dune", 412), Book("Emma", 474)])print(shelf.first_label())