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.
8 questions · take it digitally for instant feedback at tendril.neural-forge.io/learn/quiz/end-prog-python-oop-creators
What is the main idea of "Python Classes & OOP — Modeling Your World in Code"?
Which concept is most central to "Python Classes & OOP — Modeling Your World in Code"?
Which use of AI fits this topic best?
What should a careful learner remember about "Advanced: when to prefer composition"?
You want to use AI after this lesson. What is the safest next step?
How should AI output about class be treated?
Name one way to verify an AI answer about class.
Which action would help you apply "Python Classes & OOP — Modeling Your World in Code" responsibly?