Chapter DClasses and objectsPage 2 of 8

Classes and objects

Set up interfaces and contracts

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

~14 minSetup

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

Setup the chapter step

The required setup is: Python 3 is available and the class is saved in a module that a short test script can import. Confirm it before copying code. The contract separates input from output: a model name, a threshold, and numeric scores passed to predict goes in, and Boolean predictions determined by each instance's own threshold comes out. If either side is ambiguous, later debugging will chase the wrong layer.

The input contract is a model name, a threshold, and numeric scores passed to predict. The visible result is Boolean predictions determined by each instance's own threshold.

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

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__.

For the current setup 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.

Read every command or statement before running it. The examples deliberately expose intermediate state so a surprising result has somewhere concrete to point.

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?