Chapter DClasses and objectsPage 8 of 8

Classes and objects

Mastery: ship checklist

A class defines how related state and behavior belong together; each instance receives its own attributes through `__init__`.

~14 minMastery check

Before you start

Why this matters

Before running anything, predict one observable result from the case: two threshold models use the same prediction behavior but need different names and cutoffs. Write the prediction beside the command or code line that should cause it. This makes the session an experiment rather than a transcription exercise.

1Learn the idea

Read

Ship the chapter step

Shipping means handing off evidence, not only source code. Export the class from a small module with type hints and examples. Users should know construction parameters, method return types, and which validation errors are intentional. Rebuild or rerun from the documented starting point. If another person needs an undocumented fact from your machine, the handoff is incomplete.

Keep the example small enough to inspect manually. Small does not mean careless: boundary values, file locations, feature order, and held-out data still determine whether the result means what you claim.

Read

Run the working example

class TinyModel:
    def __init__(self, name, threshold=0.5):
        if not 0 <= threshold <= 1:
            raise ValueError("threshold must be between 0 and 1")
        self.name = name
        self.threshold = threshold

    def predict(self, score):
        return score >= self.threshold

strict = TinyModel("strict", 0.8)
friendly = TinyModel("friendly", 0.4)
print(strict.predict(0.6), friendly.predict(0.6))

Expected evidence:

False True

The output may include version-specific details such as hashes, paths, fitted thresholds, or final decimal places. Compare the structural facts described here rather than copying placeholders. If the structure differs, stop and inspect the earliest unexpected line.

Read

Read it line by line

  1. the class statement creates a new type; it does not create an instance.
  2. __init__ runs once per construction and rejects impossible thresholds early.
  3. self.name and self.threshold belong to that particular object.
  4. predict receives the instance automatically when called through strict or friendly.

These lines form one chain: a model name, a threshold, and numeric scores passed to predict becomes Boolean predictions determined by each instance's own threshold. Change only one input first. When several values change together, you cannot tell which change caused the new behavior.

Read

Common errors and fixes

  • First failure: omitting self from a method produces an argument-count error when the method is called. Re-run the smallest command that proves the repair.
  • Second failure: writing threshold instead of self.threshold inside predict loses access to instance state. Preserve the failing input as a test when it represents a realistic mistake.
  • Misleading success: a mutable class attribute such as history = [] is shared; create self.history = [] inside __init__ instead. A clean-looking final line cannot cancel contradictory intermediate evidence.

When debugging, copy the exact error text and inspect names, paths, shapes, types, and versions. Explain the cause in one sentence before changing code. That discipline prevents a guessed repair from creating a second defect.

Read

Evidence for this stage

The deliverable for this step is a TinyModel class whose instances validate thresholds, predict independently, and describe themselves.

For the current ship step, save the smallest useful evidence: the relevant command, its output, and the input that produced it. Do not use a screenshot as the only record when text can be copied and searched. Keep generated artifacts separate from source inputs so rerunning the example does not destroy the evidence it is meant to evaluate.

Keep constructors lightweight and avoid network or file side effects in __init__. Validate public inputs, and do not expose secret configuration through a verbose __repr__.

Read

Reflect on the result

Return to your opening prediction. Mark it correct or rewrite it with the condition you missed. Then explain the difference between a successful execution and a trustworthy result for this specific example.

Checking tutor…

Continue learning · glossary & guides
  1. Which line or command establishes the current step's most important fact?
  2. What output would reveal that writing threshold instead of self.threshold inside predict loses access to instance state?
  3. Can a new user reproduce a TinyModel class whose instances validate thresholds, predict independently, and describe themselves from the stated setup?