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__`.
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
- the class statement creates a new type; it does not create an instance.
__init__runs once per construction and rejects impossible thresholds early.self.nameandself.thresholdbelong to that particular object.predictreceives the instance automatically when called throughstrictorfriendly.
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
selffrom a method produces an argument-count error when the method is called. Re-run the smallest command that proves the repair. - Second failure: writing
thresholdinstead ofself.thresholdinsidepredictloses 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; createself.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.
Continue learning · glossary & guides
- Which line or command establishes the current step's most important fact?
- What output would reveal that writing
thresholdinstead ofself.thresholdinsidepredictloses access to instance state? - Can a new user reproduce a
TinyModelclass whose instances validate thresholds, predict independently, and describe themselves from the stated setup?