CPSC 203, 2025 W2
January 22, 2026
Every problem we solve uses some combination of these.
The pattern: learn a new tool, use it to solve a harder problem.
Today: dataclasses → bracelets
So far we’ve used built-in types: int, float, str, list, tuple…
What if we want to represent something more complex?
Python lets us define our own types using dataclasses.
What data describes a bead?
What data describes a bracelet?
A dataclass bundles related data together into a custom type.
This creates a new type called Bead with two attributes.
What would these print?
02:00
A dataclass can also have methods.
Add a draw method:
Now that you know about dataclass how would you design a Bracelet?
A bracelet contains a list of beads and has a radius.
This is composition: a Bracelet contains Beads.
The beads fit on the bracelet if the sum of their diameters is less than or equal to the circumference. We refer to the extra string as slack.
We only want to add a bead if it fits!
@dataclass
class Bead:
radius: float
colour: tuple[int, int, int]
def diameter(self) -> float: ...
def draw(self, ax, x: float, y: float) -> None: ...
@dataclass
class Bracelet:
radius: float
beads: list[Bead]
def circumference(self) -> float: ...
def slack(self) -> float: ...
def string_bead(self, bead: Bead) -> bool: ...
def remove_bead(self, index: int) -> Bead: ...
def draw(self) -> None: ...Try the Bracelet Activity on PrairieLearn!
20:00
Identify the objects in your problem (nouns)
List the data each object needs (attributes)
List the operations each object supports (methods)
Decide which object is responsible for what
Implement and test incrementally