Loading lesson…
Classes let you bundle data with the behavior that operates on it. You'll build a class for a real thing and use AI to refactor it with confidence.
A function takes inputs and returns outputs. A class groups related functions with the data they share, so you stop passing the same five arguments to every call. In 2026 Python, @dataclass makes writing classes almost free.
from dataclasses import dataclass, field
from datetime import datetime
@dataclass
class Task:
title: str
priority: int = 3
done: bool = False
created_at: datetime = field(default_factory=datetime.now)
def complete(self) -> None:
self.done = True
def age_seconds(self) -> float:
return (datetime.now() - self.created_at).total_seconds()
t = Task("Write essay", priority=1)
t.complete()
print(t) # Task(title='Write essay', priority=1, done=True, ...)@dataclass auto-generates __init__, __repr__, and __eq__. No boilerplate.@dataclass
class RecurringTask(Task):
interval_days: int = 7
def next_due(self) -> datetime:
from datetime import timedelta
return self.created_at + timedelta(days=self.interval_days)
r = RecurringTask("Water plants", interval_days=3)
print(r.next_due())
r.complete() # inherited from TaskRecurringTask gets everything Task has, plus new fields and methods.class TaskError(Exception):
"""Base class for task errors."""
class TaskAlreadyDoneError(TaskError):
pass
@dataclass
class SafeTask(Task):
def complete(self) -> None:
if self.done:
raise TaskAlreadyDoneError(f"{self.title!r} is already done")
self.done = True
try:
t = SafeTask("Study")
t.complete()
t.complete() # second call raises
except TaskAlreadyDoneError as e:
print(f"Caught: {e}")Custom exceptions let callers handle specific failures without parsing error strings.| Plain function | Class |
|---|---|
| Stateless | Holds state |
| Easy to test | Still easy with dataclass |
| Good for: one-shot logic | Good for: long-lived things (users, accounts, sessions) |
| No setup cost | A little boilerplate, a lot of clarity |
Big idea: classes model the nouns of your program. When you find yourself passing the same blob of data everywhere, it wants to be a class.
15 questions · take it digitally for instant feedback at tendril.neural-forge.io/learn/quiz/end-prog-python-oop-creators
What is the core idea behind "Python Classes & OOP — Modeling Your World in Code"?
Which term best describes a foundational idea in "Python Classes & OOP — Modeling Your World in Code"?
A learner studying Python Classes & OOP — Modeling Your World in Code would need to understand which concept?
Which of these is directly relevant to Python Classes & OOP — Modeling Your World in Code?
Which of the following is a key point about Python Classes & OOP — Modeling Your World in Code?
What is one important takeaway from studying Python Classes & OOP — Modeling Your World in Code?
Which of these does NOT belong in a discussion of Python Classes & OOP — Modeling Your World in Code?
What is the key insight about "Advanced: when to prefer composition" in the context of Python Classes & OOP — Modeling Your World in Code?
What is the recommended tip about "Always review AI output" in the context of Python Classes & OOP — Modeling Your World in Code?
Which statement accurately describes an aspect of Python Classes & OOP — Modeling Your World in Code?
What does working with Python Classes & OOP — Modeling Your World in Code typically involve?
Which best describes the scope of "Python Classes & OOP — Modeling Your World in Code"?
Which section heading best belongs in a lesson about Python Classes & OOP — Modeling Your World in Code?
Which section heading best belongs in a lesson about Python Classes & OOP — Modeling Your World in Code?
Which section heading best belongs in a lesson about Python Classes & OOP — Modeling Your World in Code?